package com.mzj.saas.mservice.property.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.haixiaoke.saas.repository.exception.BizException;
import com.haixiaoke.saas.repository.pojo.UserFloatingPopulationRecord;
import com.haixiaoke.saas.repository.service.IUserFloatingPopulationRecordService;
import com.haixiaoke.saas.repository.service.IUserService;
import com.mzj.saas.commons.*;
import com.mzj.saas.commons.enums.BacklogItemTypeEnum;
import com.mzj.saas.commons.enums.RemainingStatusEnum;
import com.mzj.saas.commons.enums.UserLoginTypeEnum;
import com.mzj.saas.commons.util.StringUtils;
import com.mzj.saas.commons.vo.redis.TokenRedisVo;
import com.mzj.saas.config.sms.SmsConfig;
import com.mzj.saas.mservice.area.entity.Area;
import com.mzj.saas.mservice.area.repository.AreaRepository;
import com.mzj.saas.mservice.auth.service.InitFaceVerifyService;
import com.mzj.saas.mservice.auth.vo.AuthenticationVo;
import com.mzj.saas.mservice.backlog.entity.BacklogItem;
import com.mzj.saas.mservice.backlog.entity.BacklogItemHouseUser;
import com.mzj.saas.mservice.backlog.repository.BacklogItemHouseUserRepository;
import com.mzj.saas.mservice.backlog.repository.BacklogItemRepository;
import com.mzj.saas.mservice.community.entity.Community;
import com.mzj.saas.mservice.community.entity.CommunityBuild;
import com.mzj.saas.mservice.community.entity.CommunityBuildUnit;
import com.mzj.saas.mservice.community.repository.CommunityBuildRepository;
import com.mzj.saas.mservice.community.repository.CommunityBuildUnitRepository;
import com.mzj.saas.mservice.community.repository.CommunityRepository;
import com.mzj.saas.mservice.community.service.AppCommunityService;
import com.mzj.saas.mservice.community.service.CommunityService;
import com.mzj.saas.mservice.department.entity.Department;
import com.mzj.saas.mservice.department.entity.UserDepartmentRef;
import com.mzj.saas.mservice.department.repository.DepartmentRepository;
import com.mzj.saas.mservice.department.repository.UserDepartmentRefRepository;
import com.mzj.saas.mservice.eligible.entity.DepartmentEnterpriseTagRef;
import com.mzj.saas.mservice.eligible.entity.DepartmentHierarchy;
import com.mzj.saas.mservice.eligible.repository.DepartmentEnterpriseTagRefRepository;
import com.mzj.saas.mservice.eligible.repository.DepartmentHierarchyRepository;
import com.mzj.saas.mservice.house.entity.House;
import com.mzj.saas.mservice.house.repository.HouseRepository;
import com.mzj.saas.mservice.house.vo.HouseVO;
import com.mzj.saas.mservice.lock.Repository.*;
import com.mzj.saas.mservice.lock.entity.*;
import com.mzj.saas.mservice.lock.service.LockAppService;
import com.mzj.saas.mservice.oss.service.OSSService;
import com.mzj.saas.mservice.property.entity.*;
import com.mzj.saas.mservice.property.repository.*;
import com.mzj.saas.mservice.property.vo.*;
import com.mzj.saas.mservice.smartlock.service.SmartLockBrandService;
import com.mzj.saas.mservice.sms.service.SmsService;
import com.mzj.saas.mservice.sys.entity.AppUser;
import com.mzj.saas.mservice.sys.entity.User;
import com.mzj.saas.mservice.sys.repository.AppUserRepository;
import com.mzj.saas.mservice.sys.repository.UserRepository;
import com.mzj.saas.mservice.sys.utils.SqlUtils;
import com.mzj.saas.redis.RedisService;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang3.RandomUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author hikari
 * @since 2021-05-25
 */
@Service
public class CommunityHouseUserService {

    private static final Logger log = LoggerFactory.getLogger(CommunityHouseUserService.class);

    @Value("${contract.tmp.dir}")
    private String contractTmpDir;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
    @Autowired
    private RedisService redisService;
    @Autowired
    private OSSService ossService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private SmsConfig smsConfig;
    @Autowired
    private PropertyCommunityHouseService propertyCommunityHouseService;
    @Autowired
    private CommunityHouseUserRepository communityHouseUserRepository;
    @Autowired
    private AppUserRepository appUserRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private AppCommunityService appCommunityService;
    @Autowired
    private SmartLockRepository smartLockRepository;
    @Autowired
    private SmartLockAuthRepository smartLockAuthRepository;
    @Autowired
    private LockAppService lockAppService;
    @Autowired
    private MatchUserHouseRepository matchUserHouseRepository;
    @Autowired
    private MatchUserRepository matchUserRepository;
    @Autowired
    private MatchUserLockAuthorRepository matchUserLockAuthorRepository;
    @Autowired
    private BacklogItemRepository backlogItemRepository;
    @Autowired
    private HouseRepository houseRepository;
    @Autowired
    private BacklogItemHouseUserRepository backlogItemHouseUserRepository;
    @Autowired
    private DepartmentHierarchyRepository departmentHierarchyRepository;
    @Autowired
    private CommunityService communityService;
    @Autowired
    private HouseRemainingRepository houseRemainingRepository;
    @Autowired
    private HouseRemainingRecordRepository houseRemainingRecordRepository;
    @Autowired
    private HouseRemainingRelationRepository houseRemainingRelationRepository;
    @Autowired
    private EstateExpenseBillRepository estateExpenseBillRepository;
    @Autowired
    private EstateRentBillRepository estateRentBillRepository;
    @Autowired
    private CommunityRepository communityRepository;
    @Autowired
    private DepartmentEnterpriseTagRefRepository departmentEnterpriseTagRefRepository;
    @Autowired
    private AreaRepository areaRepository;
    @Autowired
    @Qualifier("stringRedisTemplate")
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserDepartmentRefRepository userDepartmentRefRepository;
    @Autowired
    private DepartmentRepository departmentRepository;
    @Autowired
    private DepartmentRemainingRepository departmentRemainingRepository;
    @Autowired
    private DepartmentRemainingRefRepository departmentRemainingRefRepository;
    @Autowired
    private DepartmentRemainingRecordRepository departmentRemainingRecordRepository;
    @Autowired
    private IUserFloatingPopulationRecordService userFloatingPopulationRecordService;
    @Autowired
    private SmartLockBrandService smartLockBrandService;
    @Autowired
    private SmartLockFaceRepository smartLockFaceRepository;
    @Autowired
    private CommunityBuildRepository communityBuildRepository;
    @Autowired
    private CommunityBuildUnitRepository communityBuildUnitRepository;
    @Autowired
    private LockOpenLogRepository lockOpenLogRepository;
    @Autowired
    private IUserService iUserService;
    @Autowired
    private InitFaceVerifyService initFaceVerifyService;


    @Value("${ali.oss.bucket.url}")
    private String ossBucketUrl;

    @Value("${ali.faceAuthentication.host}")
    private String aliFaceAuthenticationHost;

    @Value("${ali.faceAuthentication.path}")
    private String aliFaceAuthenticationPath;

    @Value("${ali.faceAuthentication.appcode}")
    private String aliFaceAuthenticationAppcode;

    @Value("${ali.eidAuthentication.appcode}")
    private String aliEidAuthenticationAppcode;

    @Value("${ali.eidAuthentication.url}")
    private String aliEidAuthenticationUrl;

    /**
     * 新增|修改房屋成员
     *
     * @param accessToken
     * @param saveOrEditVO
     * @return 新增房屋成员 新增同住人关系为女儿\儿子为手机号添加后缀 新增同住人时手机号|身份证不可重复 个人承租人只可绑定一套房屋
     * 新增成功后推送待办事项
     */
    @Transactional
    public ResultBean<Object> saveOrEdit(String accessToken, SaveOrEditVO saveOrEditVO) {
        log.info("accessToken{}", accessToken);
        log.info("saveOrEditVo{}", JSON.toJSONString(saveOrEditVO.getCommunityHouseUsers()));
        log.info("saveOrEditVo MatchUserHouseVO {}", JSON.toJSONString(saveOrEditVO.getMatchUserHouseVO()));
        TokenRedisVo token = redisService.findTokenVo(accessToken);
        if (token == null) {
            return ResultBean.failedResultOfToken();
        }
        Long enterpriseId = token.getEnterpriseId();
        Date date = new Date();

        MatchUserHouseVO muhVO = saveOrEditVO.getMatchUserHouseVO();
        if (muhVO == null) {
            return ResultBean.failedResultWithMsg("租户信息有误");
        }

        List<CommunityHouseUser> communityHouseUsers1 = saveOrEditVO.getCommunityHouseUsers();

        List<House> houses = houseRepository.findByIdAndStatus(communityHouseUsers1.get(communityHouseUsers1.size() - 1).getCommunityHouseId(), 1);
        if (CollectionUtil.isNotEmpty(houses)) {
            Integer leaseStatus = houses.get(0).getLeaseStatus();
            if (leaseStatus == 2) {
                return ResultBean.failedResultWithMsg("房屋已过期不可入住");
            }
            if (leaseStatus == 3) {
                return ResultBean.failedResultWithMsg("房屋退租中不可入住");
            }
        }

        AppUser newAppUser = null;
        for (CommunityHouseUser communityHouseUser : communityHouseUsers1) {
            if (communityHouseUser.getType() == 2 && communityHouseUser.getRelationTag() == null) {
                return ResultBean.failedResultWithMsg("请选择与承租人关系");
            }
            if (StrUtil.isEmpty(communityHouseUser.getName())) {
                return ResultBean.failedResultWithMsg("请填写同住人姓名");
            }
            String sql = "SELECT mobile FROM saas_community_house_user WHERE community_house_id = ? AND `status` = 1 AND type != 1";
            List<CommunityHouseUser> communityHouseUserList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(CommunityHouseUser.class), communityHouseUser.getCommunityHouseId());
            if (communityHouseUser.getId() == null) {
                for (CommunityHouseUser houseUser : communityHouseUserList) {
                    if (houseUser.getMobile().equals(communityHouseUser.getMobile())) {
                        return ResultBean.failedResultWithMsg("成员手机号码不能重复");
                    }
                }


                //     检验合租房子下面的子房间中不能出现相同手机号
                List<House> byIdAndStatus = houseRepository.findByIdAndStatus(communityHouseUser.getCommunityHouseId(), 1);
                Integer relationTag = communityHouseUser.getRelationTag() == null ? 0 : communityHouseUser.getRelationTag();
                if (byIdAndStatus.get(0).getMatchType() == 2) {
                    List<House> byHousemateIdAndStatus = houseRepository.findByHousemateIdAndStatus(byIdAndStatus.get(0).getId(), 1);
                    if (CollectionUtil.isNotEmpty(byHousemateIdAndStatus)) {
                        for (House housemateIdAndStatus : byHousemateIdAndStatus) {
                            List<CommunityHouseUser> communityHouseUsers = communityHouseUserRepository.findByCommunityHouseIdAndStatusAndMobile(housemateIdAndStatus.getId(), 1, communityHouseUser.getMobile());
                            if (CollectionUtil.isNotEmpty(communityHouseUsers) && !(relationTag == 3 || relationTag == 5)) {
                                return ResultBean.failedResultWithMsg("合租房间中成员手机号码不能重复");
                            }

                        }
                    }
                }
                if (StrUtil.isNotBlank(byIdAndStatus.get(0).getHousemateId())) {
                    List<House> byHousemateIdAndStatus = houseRepository.findByHousemateIdAndStatus(byIdAndStatus.get(0).getHousemateId(), 1);
                    if (CollectionUtil.isNotEmpty(byHousemateIdAndStatus)) {
                        for (House housemateIdAndStatus : byHousemateIdAndStatus) {
                            List<CommunityHouseUser> communityHouseUsers = communityHouseUserRepository.findByCommunityHouseIdAndStatusAndMobile(housemateIdAndStatus.getId(), 1, communityHouseUser.getMobile());
                            if (CollectionUtil.isNotEmpty(communityHouseUsers) && !(relationTag == 3 || relationTag == 5)) {
                                return ResultBean.failedResultWithMsg("合租房间中成员手机号码不能重复");
                            }

                        }
                    }
                }


            }


            if (communityHouseUser.getType() != 4) {
                if (StrUtil.isEmpty(communityHouseUser.getCardNumber())) {
                    return ResultBean.failedResultOfParamWithMsg("请输入身份证号");
                }

                if (!IdcardUtil.isValidCard(communityHouseUser.getCardNumber())) {
                    return ResultBean.failedResultOfParamWithMsg("请输入正确的身份证号");
                }
            }

            //     承租人如果没有appUser信息，给他新增一个appUser信息
            if (communityHouseUser.getType() == 1) {
                AppUser appUser = appUserRepository.findByCardNumberAndStatusAndType(communityHouseUser.getCardNumber(), 1, UserLoginTypeEnum.CONSUMER.getValue());
                if (ObjectUtil.isNotEmpty(appUser)) {
                    if (!appUser.getPhone().equals(communityHouseUser.getMobile())) {
                        return ResultBean.failedResultOfParamWithMsg("该身份证号：" + communityHouseUser.getCardNumber() + ",已绑定" + appUser.getPhone() + "手机号");
                    }
                } else {
                    AppUser appUser1 = appUserRepository.findByPhoneAndTypeAndStatus(communityHouseUser.getMobile(), UserLoginTypeEnum.CONSUMER.getValue(), 1);
                    if (ObjectUtil.isEmpty(appUser1)) {
                        byte[] salt = Digests.generateSalt(8);
                        String saltStr = Encodes.encodeHex(salt);
                        AppUser addAppUser = new AppUser();
                        addAppUser.setId("S" + KeyWorker.nextId());
                        addAppUser.setName(communityHouseUser.getName());
                        addAppUser.setPhone(communityHouseUser.getMobile());
                        addAppUser.setPassword(null);
                        addAppUser.setSalt(saltStr);
                        addAppUser.setType(2);// 小程序用户
                        addAppUser.setCertificationStatus(0);
                        addAppUser.setCardNumber(communityHouseUser.getCardNumber());
                        addAppUser.setStatus(1);
                        addAppUser.setRegistrationTime(new Date());
                        newAppUser = appUserRepository.save(addAppUser);
                    }

                }

            }


        }
        if (muhVO.getLabel() == null) {
            return ResultBean.failedResultWithMsg("承租人类型不能为空");
        }

        if (saveOrEditVO.getMatchType() == null) {
            saveOrEditVO.setMatchType(1);
        }

        // 新建子房屋
        House newHouse = new House();
        List<CommunityHouseUserVO> voList = new ArrayList<>();
        // 判断配置方式是整租还是合租 配租方式：1(整租)  2合租）
        if (saveOrEditVO.getMatchType() != null) {
            if (saveOrEditVO.getMatchType() == 2) {
                if (saveOrEditVO.getRoomnumber() == "") {
                    return ResultBean.failedResultWithMsg("请输入房间号");
                }
                // 获取前端传过来的成员信息
                List<CommunityHouseUser> communityHouseUsers = saveOrEditVO.getCommunityHouseUsers();
                // 实现在合租房产下的房屋下添加成员
                String communityHouseId1 = communityHouseUsers.get(0).getCommunityHouseId();
                String roomnumber = saveOrEditVO.getRoomnumber();
                // 获取合租房产下的房屋号的房产信息,如果存在则是在合租房产下的房屋下添加成员，不是这是直接添加
                List<House> byHousemateIdAndStatusAndRoomNumber = houseRepository.findByHousemateIdAndStatusAndRoomNumber(communityHouseId1, 1, roomnumber);
                if (byHousemateIdAndStatusAndRoomNumber.size() > 0) {
                    // 获取合租房产下房屋id
                    String id = byHousemateIdAndStatusAndRoomNumber.get(0).getId();
                    for (CommunityHouseUser communityHouseUser : communityHouseUsers) {
                        // 把前端传过来的成员房屋id全部更换为合租房产下房屋id
                        communityHouseUser.setCommunityHouseId(id);
                    }
                }
                ArrayList<String> communityHouseIds = new ArrayList<>();
                Long UnitLesseeId = muhVO.getId();
                for (CommunityHouseUser communityHouseUser : communityHouseUsers) {
                    String communityHouseId = communityHouseUser.getCommunityHouseId();
                    communityHouseIds.add(communityHouseId);
                }
                // 获取房屋信息
                List<House> byIdIn = houseRepository.findByIdIn(communityHouseIds);
                Long provinceId = byIdIn.get(0).getProvinceId();
                String roomNumber = byIdIn.get(0).getRoomNumber();// 房屋号
                String voRoomnumber = saveOrEditVO.getRoomnumber();
                String housemateId = byIdIn.get(0).getHousemateId();// 获取合租房屋id
                // 如果已经是合租房屋下的子房屋，就不能再创建子房屋了
                // if (housemateId != null && saveOrEditVO.getMatchType() == 2) {
                // 	return ResultBean.failedResultWithMsg("已是合租房产下的房屋，不可再创建房产！");
                // }

                // 特殊关系的同住人，如果手机号码与承租人相同，重置同住人手机号码，增加后缀（确保手机号字段唯一）
                int count = 0;
                for (CommunityHouseUser chu : saveOrEditVO.getCommunityHouseUsers()) {
                    for (CommunityHouseUser vo : saveOrEditVO.getCommunityHouseUsers()) {
                        Integer mobileStatus = vo.getMobileStatus();
                        if (mobileStatus == null) {
                            vo.setMobileStatus(1);
                        }
                        // 1妻子、2丈夫、3儿子、4儿媳、5女儿、6女婿、7父亲、8母亲、9同事、10哥哥、11嫂子、12姐姐、13姐夫、14弟弟、15弟媳、16妹妹、17妹夫、18其他亲属、19朋友、20非亲属
                        if (chu.getType() != null
                                && chu.getType() == 1
                                && chu.getMobile().equals(vo.getMobile())
                                && vo.getRelationTag() != null
                                && vo.getType() != null
                                && vo.getType() == 2
                                && (vo.getRelationTag() == 3 || vo.getRelationTag() == 5 || vo.getMobileStatus() == 0)) {
                            vo.setMobile(vo.getMobile() + "_" + count);
                            count++;
                        }
                    }
                }

                List<String> mobiles = saveOrEditVO.getCommunityHouseUsers().stream().map(mm -> mm.getMobile()).distinct().collect(Collectors.toList());
                if (mobiles.size() < saveOrEditVO.getCommunityHouseUsers().size()) {
                    return ResultBean.failedResultWithMsg("成员手机号码不能重复");
                }

                List<String> cardNumbers1 = saveOrEditVO.getCommunityHouseUsers().stream().filter(mm -> StringUtils.isNotBlank(mm.getCardNumber())).map(mm -> mm.getCardNumber()).collect(Collectors.toList());
                List<String> cardNumbers2 = saveOrEditVO.getCommunityHouseUsers().stream().filter(mm -> StringUtils.isNotBlank(mm.getCardNumber())).map(mm -> mm.getCardNumber()).distinct().collect(Collectors.toList());
                if (cardNumbers1.size() != cardNumbers2.size()) {
                    return ResultBean.failedResultWithMsg("成员身份证号码不能重复");
                }

                // 房屋号去重
                if (housemateId == null && roomNumber.equals(voRoomnumber)) {
                    return ResultBean.failedResultWithMsg("房产不可以重复！");
                }
                // 公租房需要去重
                String mobileSql = "SELECT distinct tt.mobile FROM ("
                        + "SELECT hu.mobile, hu.card_number FROM saas_community_house_user hu WHERE hu.type = 2 AND hu.status = 1 "
                        + "UNION ALL "
                        + "SELECT hu.mobile, hu.card_number FROM saas_community_house_user hu LEFT JOIN m_match_user_house uh ON hu.community_house_id = uh.house_id "
                        + "WHERE uh.label = 1 AND hu.status = 1 ) tt";


                List<CommunityHouseUser> matchUsers = jdbcTemplate.query(mobileSql, new BeanPropertyRowMapper<>(CommunityHouseUser.class));
                Map<String, CommunityHouseUser> mobileMap = matchUsers.stream().collect(Collectors.toMap(CommunityHouseUser::getMobile, CommunityHouseUser -> CommunityHouseUser));

                String cardSql = "SELECT distinct tt.card_number FROM ("
                        + "SELECT hu.mobile, hu.card_number FROM saas_community_house_user hu WHERE hu.type = 2 AND hu.status = 1 "
                        + "UNION ALL "
                        + "SELECT hu.mobile, hu.card_number FROM saas_community_house_user hu LEFT JOIN m_match_user_house uh ON hu.community_house_id = uh.house_id "
                        + "WHERE uh.label = 1 AND hu.status = 1 ) tt";
                List<CommunityHouseUser> cardUsers = jdbcTemplate.query(cardSql, new BeanPropertyRowMapper<>(CommunityHouseUser.class));
                Map<String, CommunityHouseUser> cardMap = cardUsers.stream().filter(ff -> StringUtils.isNotBlank(ff.getCardNumber())).collect(Collectors.toMap(CommunityHouseUser::getCardNumber, CommunityHouseUser -> CommunityHouseUser));

                // 获取房屋id,设置房屋为已出租状态
                String voHouseId = muhVO.getHouseId();
                Optional<House> byId2 = houseRepository.findById(voHouseId);

                // 获取房屋类型：性质:1公租房、2保障房、3出租房、4自用房、5单位宿舍
                Integer houseNature = byId2.get().getHouseNature();
                if (houseNature == 1 || houseNature == 2) {
                    for (CommunityHouseUser communityHouseUser : saveOrEditVO.getCommunityHouseUsers()) {
                        // 新增
                        if (communityHouseUser.getId() == null) {
                            List<CommunityHouseUser> entity = communityHouseUserRepository.findByMobileAndStatus(communityHouseUser.getMobile(), 1);
                            // if (mobileMap.get(communityHouseUser.getMobile()) != null) {
                            //	return ResultBean
                            //			.failedResultWithMsg("手机：" + communityHouseUser.getMobile() + "，已绑定其它房产，不能重复添加");
                            //}

                            // if(StringUtils.isNoneBlank(communityHouseUser.getCardNumber())){
                            //	//List<CommunityHouseUser> entity2 = communityHouseUserRepository.findByCardNumberAndStatus(communityHouseUser.getCardNumber(), 1);
                            //	if (cardMap.get(communityHouseUser.getCardNumber()) != null) {
                            //		return ResultBean.failedResultWithMsg(
                            //				"身份证：" + communityHouseUser.getCardNumber() + "，已绑定其它房产，不能重复添加");
                            //	}
                            //}
                            // 如果是在出租房住的，还能再进保障房入住
                            if (!entity.isEmpty() && communityHouseUser.getType() != 4) {
                                for (CommunityHouseUser houseUser : entity) {
                                    String communityHouseId = houseUser.getCommunityHouseId();
                                    List<House> byIdAndStatus = houseRepository.findByIdAndStatus(communityHouseId, 1);
                                    if (!byIdAndStatus.isEmpty()) {
                                        House house = byIdAndStatus.get(0);
                                        Integer houseNature1 = house.getHouseNature();
                                        if (houseNature1 == 1 || houseNature1 == 2) {
                                            if (houseUser.getType() != 4) {
                                                return ResultBean.failedResultWithMsg("手机：" + communityHouseUser.getMobile() + "，已绑定其它房产，不能重复添加");
                                            }
                                        }
                                    }
                                }
                            }

                        }

                        // 编辑
                        if (communityHouseUser.getId() != null) {
                            Optional<CommunityHouseUser> houseUserOptional = communityHouseUserRepository
                                    .findById(communityHouseUser.getId());
                            CommunityHouseUser houseUser = houseUserOptional.get();
                            // if (!houseUser.getMobile().equals(communityHouseUser.getMobile())) {
                            //     // List<CommunityHouseUser> entity = communityHouseUserRepository.findByMobileAndStatus(communityHouseUser.getMobile(), 1);
                            //     if (mobileMap.get(communityHouseUser.getMobile()) != null) {
                            //         if (communityHouseUser.getType() != 4) {
                            //             return ResultBean.failedResultWithMsg("手机：" + communityHouseUser.getMobile() + "，已绑定其它房产，不能重复添加");
                            //         }
                            //     }
                            // }

                            // 验证身份证
                            if (StringUtils.isNotBlank(communityHouseUser.getCardNumber()) && !communityHouseUser.getCardNumber().equals(houseUser.getCardNumber())) {
                                // List<CommunityHouseUser> entity2 = communityHouseUserRepository.findByCardNumberAndStatus(communityHouseUser.getCardNumber(), 1);
                                if (cardMap.get(communityHouseUser.getCardNumber()) != null) {
                                    if (communityHouseUser.getType() != 4) {
                                        return ResultBean.failedResultWithMsg("身份证：" + communityHouseUser.getCardNumber() + "，已绑定其它房产，不能重复添加");
                                    }
                                }
                            }
                        }
                    }
                }
                // 如果是合租房就把房子改成合租出租中和出租类型改成合租
                // 出租状态：0未出租 1已出租 2已过期 3退租中 4合租出租中
                if (housemateId == null && byIdIn != null) {
                    byIdIn.get(0).setMatchType(2);
                    houseRepository.save(byIdIn.get(0));
                }
                // 如果是修改/新增的话就不用新创建房屋信息了
                if (housemateId != null && roomNumber.equals(voRoomnumber)) {
                    BeanUtils.copyProperties(byIdIn.get(0), newHouse);
                } else {
                    // 获取当省份的3个首字母
                    Area area = areaRepository.findByIdAndLevel(provinceId, 1);
                    String province = pinyin(area.getName());// 省份3个首字母


                    // 生成房屋id=省份首字母+时间戳+随机数
                    String newId = province + System.currentTimeMillis() + RandomUtils.nextInt(1000, 10000);// 省份3位首字母 + 10数字
                    House house1 = byIdIn.get(0);
                    String id1 = house1.getId();
                    // 查询出合租房产的房间号
                    List<House> byIdAndStatus = houseRepository.findByIdAndStatus(id1, 1);
                    String roomNumber1 = byIdAndStatus.get(0).getRoomNumber();
                    // 合租房产下的房间号，拼接上父房产的房间号
                    roomNumber1 = roomNumber + "-" + saveOrEditVO.getRoomnumber();
                    BeanUtils.copyProperties(house1, newHouse);
                    newHouse.setId(newId);  // 生成id
                    newHouse.setHousemateId(id1);// 关联上合租房屋id
                    newHouse.setLeaseStatus(1);// 设置房屋为已出租
                    newHouse.setRoomNumber(roomNumber1);// 合租房屋号
                    newHouse.setStatus(1);
                    newHouse.setMatchType(1);
                    newHouse.setCreateTime(new Date());
                    newHouse.setUnitLesseeId(UnitLesseeId);
                    houseRepository.save(newHouse);
                    // 新增合租房产子房产智能锁与房屋信息，如果存在则新增
                    List<SmartLock> byHouseId = smartLockRepository.findByHouseId(id1);
                    if (!byHouseId.isEmpty()) {
                        SmartLock smartLock = new SmartLock();
                        BeanUtils.copyProperties(byHouseId.get(0), smartLock);
                        smartLock.setId(null);
                        smartLock.setHouseId(newId);
                        smartLock.setStatus(2);
                        smartLockRepository.save(smartLock);
                    }

                    if (muhVO.getLabel() == 2) {
                        //	如果是单位承租人则没有添加承租人信息，得自己添加单位承租人为承租人
                        MatchUserHouseVO matchUserHouseVO = saveOrEditVO.getMatchUserHouseVO();
                        if (matchUserHouseVO != null) {

                            Long id4 = matchUserHouseVO.getId();
                            List<UserDepartmentRef> byDepId = userDepartmentRefRepository.findByDepId(id4);
                            String userId = byDepId.get(0).getUserId();
                            // 获取单位承租人机构用户信息
                            User byId = userRepository.findById(userId);
                            String id2 = byId.getId();
                            String name = byId.getName();
                            List<UserDepartmentRef> byUserId = userDepartmentRefRepository.findByUserId(id2);
                            // 获取机构名称
                            if (!byUserId.isEmpty()) {
                                Long depId = byUserId.get(0).getDepId();
                                Optional<Department> byId1 = departmentRepository.findById(depId);
                                String name1 = byId1.get().getName();
                                name = name1;
                            }
                            // 获取承租人库信息
                            MatchUser byMatchUserId = matchUserRepository.findByMatchUserId(id2);
                            if (byMatchUserId == null) {
                                // 新增承租人库
                                MatchUser matchUser = new MatchUser();
                                matchUser.setMatchUserId(id2);
                                matchUser.setName(name);
                                matchUser.setPhone(byId.getMobile());
                                matchUser.setDeleteStatus(false);
                                matchUser.setCraeteUserId(token.getId());
                                matchUser.setCreateTime(new Date());
                                matchUser.setLastUpdateTime(new Date());
                                matchUserRepository.save(matchUser);
                            }
                            //	获取承租人智能锁信息
                            // MatchUserLockAuthor byMatchUserStock = matchUserLockAuthorRepository.findByHouseId(newHouse.getId());
                            List<MatchUserLockAuthor> byMatchUserStockList = matchUserLockAuthorRepository.findByHouseId(newHouse.getId());
                            if (byMatchUserStockList.size() < 1) {
                                byMatchUserId = matchUserRepository.findByMatchUserId(id2);
                                Long id3 = null;
                                if (byMatchUserId != null) {
                                    id3 = byMatchUserId.getId();
                                }
                                MatchUserLockAuthor byMatchUserStock = new MatchUserLockAuthor();
                                byMatchUserStock.setCreateTime(new Date());
                                byMatchUserStock.setOperatorUserId(1l);
                                // 同时插入临时密码次数记录
                                // 生效年月
                                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");
                                byMatchUserStock.setEffectiveJulyDate(dateFormat.format(new Date()));
                                byMatchUserStock.setHouseId(newHouse.getId());
                                byMatchUserStock.setMatchUserStockId(id3 + "");
                                // 默认5次
                                byMatchUserStock.setAuthorNumber(5);
                                // 默认1天
                                byMatchUserStock.setPasswordValidity(1);
                                byMatchUserStock.setUseNumber(0);
                                byMatchUserStock.setLastUpdateTime(new Date());
                                matchUserLockAuthorRepository.save(byMatchUserStock);
                            }
                            // 先查一遍数据库中是否有该承租人和房屋的关系，根据房屋id查询，没有就更新
                            List<MatchUserHouse> byHouseList = matchUserHouseRepository.findByHouseId(newHouse.getId());
                            MatchUserHouse matchUserHouse = null;
                            if (byHouseList.size() < 1) {
                                matchUserHouse = new MatchUserHouse();
                                byMatchUserId = matchUserRepository.findByMatchUserId(id2);
                                Long id3 = null;
                                if (byMatchUserId != null) {
                                    id3 = byMatchUserId.getId();
                                }
                                matchUserHouse.setMatchUserStockId(id3 + "");
                                matchUserHouse.setHouseId(newHouse.getId());
                                // List<CommunityHouseUser> users = communityHouseUserRepository.findByCommunityHouseIdAndStatusAndType(houseId, 1, 1);
                                // matchUserHouse.setMemberUserId(!users.isEmpty() ? users.get(0).getId() : null);
                                matchUserHouse.setLabel(matchUserHouseVO.getLabel());
                                matchUserHouse.setCompanyName(matchUserHouseVO.getCompanyName());
                                matchUserHouse.setSocialCreditNumber(matchUserHouseVO.getSocialCreditNumber());
                                matchUserHouse.setStartDate(matchUserHouseVO.getStartDate());
                                matchUserHouse.setEndDate(matchUserHouseVO.getEndDate());
                                matchUserHouse.setChargeMode(matchUserHouseVO.getChargeMode());
                                matchUserHouse.setCreateTime(new Date());
                                // 承租人和房屋关系表
                                matchUserHouseRepository.save(matchUserHouse);
                            }
                        }
                    } else {
                        //	如果是产权单位或者物业合租也得自己添加承租人
                        MatchUserHouseVO matchUserHouseVO = saveOrEditVO.getMatchUserHouseVO();
                        if (matchUserHouseVO != null) {
                            List<UserDepartmentRef> byDepId = userDepartmentRefRepository.findByDepId(enterpriseId);
                            if (byDepId.size() > 0) {
                                String userId = byDepId.get(0).getUserId();
                                // 获取单位承租人机构用户信息
                                User byId = userRepository.findById(userId);
                                String id2 = byId.getId();
                                String name = byId.getName();
                                List<UserDepartmentRef> byUserId = userDepartmentRefRepository.findByUserId(id2);
                                // 获取机构名称
                                if (!byUserId.isEmpty()) {
                                    Long depId = byUserId.get(0).getDepId();
                                    Optional<Department> byId1 = departmentRepository.findById(depId);
                                    String name1 = byId1.get().getName();
                                    name = name1;
                                }
                                // 获取承租人库信息
                                MatchUser byMatchUserId = matchUserRepository.findByMatchUserId(id2);
                                if (byMatchUserId == null) {
                                    // 新增承租人库
                                    MatchUser matchUser = new MatchUser();
                                    matchUser.setMatchUserId(id2);
                                    matchUser.setName(name);
                                    matchUser.setPhone(byId.getMobile());
                                    matchUser.setDeleteStatus(false);
                                    matchUser.setCraeteUserId(token.getId());
                                    matchUser.setCreateTime(new Date());
                                    matchUser.setLastUpdateTime(new Date());
                                    matchUserRepository.save(matchUser);
                                }
                                //	获取承租人智能锁信息
                                // MatchUserLockAuthor byMatchUserStock = matchUserLockAuthorRepository.findByHouseId(newHouse.getId());
                                List<MatchUserLockAuthor> byMatchUserStockList = matchUserLockAuthorRepository.findByHouseId(matchUserHouseVO.getHouseId());
                                if (byMatchUserStockList.size() < 1) {
                                    byMatchUserId = matchUserRepository.findByMatchUserId(id2);
                                    Long id3 = null;
                                    if (byMatchUserId != null) {
                                        id3 = byMatchUserId.getId();
                                    }
                                    MatchUserLockAuthor byMatchUserStock = new MatchUserLockAuthor();
                                    byMatchUserStock.setCreateTime(new Date());
                                    byMatchUserStock.setOperatorUserId(1l);
                                    // 同时插入临时密码次数记录
                                    // 生效年月
                                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");
                                    byMatchUserStock.setEffectiveJulyDate(dateFormat.format(new Date()));
                                    byMatchUserStock.setHouseId(matchUserHouseVO.getHouseId());
                                    byMatchUserStock.setMatchUserStockId(id3 + "");
                                    // 默认5次
                                    byMatchUserStock.setAuthorNumber(5);
                                    // 默认1天
                                    byMatchUserStock.setPasswordValidity(1);
                                    byMatchUserStock.setUseNumber(0);
                                    byMatchUserStock.setLastUpdateTime(new Date());
                                    matchUserLockAuthorRepository.save(byMatchUserStock);
                                }
                                // 先查一遍数据库中是否有该承租人和房屋的关系，根据房屋id查询，没有就更新
                                // 产权机构和物业机构 如果是合租下的房屋，不用机构自己添加承租人
                                List<House> byHousemateIdAndStatus = houseRepository.findByIdAndStatus(newHouse.getId(), 1);
                                if (byHousemateIdAndStatus.get(0).getHousemateId() == null) {
                                    List<MatchUserHouse> byHouseList = matchUserHouseRepository.findByHouseId(newHouse.getId());
                                    MatchUserHouse matchUserHouse = null;
                                    if (byHouseList.size() < 1) {
                                        matchUserHouse = new MatchUserHouse();
                                        byMatchUserId = matchUserRepository.findByMatchUserId(id2);
                                        Long id3 = null;
                                        if (byMatchUserId != null) {
                                            id3 = byMatchUserId.getId();
                                        }
                                        matchUserHouse.setMatchUserStockId(id3 + "");
                                        matchUserHouse.setHouseId(newHouse.getId());
                                        // List<CommunityHouseUser> users = communityHouseUserRepository.findByCommunityHouseIdAndStatusAndType(houseId, 1, 1);
                                        // matchUserHouse.setMemberUserId(!users.isEmpty() ? users.get(0).getId() : null);
                                        matchUserHouse.setLabel(matchUserHouseVO.getLabel());
                                        matchUserHouse.setCompanyName(matchUserHouseVO.getCompanyName());
                                        matchUserHouse.setSocialCreditNumber(matchUserHouseVO.getSocialCreditNumber());
                                        matchUserHouse.setStartDate(matchUserHouseVO.getStartDate());
                                        matchUserHouse.setEndDate(matchUserHouseVO.getEndDate());
                                        matchUserHouse.setChargeMode(matchUserHouseVO.getChargeMode());
                                        matchUserHouse.setCreateTime(new Date());
                                        // 承租人和房屋关系表
                                        matchUserHouseRepository.save(matchUserHouse);
                                    }
                                }

                            }
                        }

                    }
                }

                // 新增单位承租人标签，承租人类型如果选择的是单位承租人，让其所选的单位机构有对应的房屋权限
                if (muhVO.getLabel() == 2) {
                    if (byIdIn != null) {
                        for (House house : byIdIn) {
                            // 关联上单位承租人id
                            house.setUnitLesseeId(UnitLesseeId);
                            houseRepository.save(house);
                        }
                    }
                    //	如果是单位承租人机构则没有添加承租人信息，得自己添加单位承租人机构为承租人
                    MatchUserHouseVO matchUserHouseVO = saveOrEditVO.getMatchUserHouseVO();
                    Long id1 = matchUserHouseVO.getId();
                    List<UserDepartmentRef> byDepId = userDepartmentRefRepository.findByDepId(id1);
                    String userId = byDepId.get(0).getUserId();
                    // 获取单位承租人机构用户信息
                    User byId = userRepository.findById(userId);
                    String id2 = byId.getId();
                    String name = byId.getName();
                    List<UserDepartmentRef> byUserId = userDepartmentRefRepository.findByUserId(id2);
                    // 获取机构名称
                    if (!byUserId.isEmpty()) {
                        Long depId = byUserId.get(0).getDepId();
                        Optional<Department> byId1 = departmentRepository.findById(depId);
                        String name1 = byId1.get().getName();
                        name = name1;
                    }
                    // 获取承租人库信息
                    MatchUser byMatchUserId = matchUserRepository.findByMatchUserId(id2);
                    if (byMatchUserId == null) {
                        // 新增承租人库
                        MatchUser matchUser = new MatchUser();
                        matchUser.setMatchUserId(id2);
                        matchUser.setName(name);
                        matchUser.setPhone(byId.getMobile());
                        matchUser.setDeleteStatus(false);
                        matchUser.setCraeteUserId(token.getId());
                        matchUser.setCreateTime(new Date());
                        matchUser.setLastUpdateTime(new Date());
                        matchUserRepository.save(matchUser);
                    }
                    //	获取承租人智能锁信息
                    // MatchUserLockAuthor byMatchUserStock = matchUserLockAuthorRepository.findByHouseId(matchUserHouseVO.getHouseId());
                    List<MatchUserLockAuthor> byMatchUserStockList = matchUserLockAuthorRepository.findByHouseId(matchUserHouseVO.getHouseId());
                    if (byMatchUserStockList.size() < 1) {
                        byMatchUserId = matchUserRepository.findByMatchUserId(id2);
                        Long id3 = null;
                        if (byMatchUserId != null) {
                            id3 = byMatchUserId.getId();
                        }
                        MatchUserLockAuthor byMatchUserStock = new MatchUserLockAuthor();
                        byMatchUserStock.setCreateTime(new Date());
                        byMatchUserStock.setOperatorUserId(1l);
                        // 同时插入临时密码次数记录
                        // 生效年月
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");
                        byMatchUserStock.setEffectiveJulyDate(dateFormat.format(new Date()));
                        byMatchUserStock.setHouseId(matchUserHouseVO.getHouseId());
                        byMatchUserStock.setMatchUserStockId(id3 + "");
                        // 默认5次
                        byMatchUserStock.setAuthorNumber(5);
                        // 默认1天
                        byMatchUserStock.setPasswordValidity(1);
                        byMatchUserStock.setUseNumber(0);
                        byMatchUserStock.setLastUpdateTime(new Date());
                        matchUserLockAuthorRepository.save(byMatchUserStock);
                    }
                    // 先查一遍数据库中是否有该承租人和房屋的关系，根据房屋id查询，有就更新
                    List<MatchUserHouse> byHouseList = matchUserHouseRepository.findByHouseId(matchUserHouseVO.getHouseId());
                    MatchUserHouse matchUserHouse = null;
                    if (byHouseList.size() < 1) {
                        matchUserHouse = new MatchUserHouse();
                        byMatchUserId = matchUserRepository.findByMatchUserId(id2);
                        Long id3 = null;
                        if (byMatchUserId != null) {
                            id3 = byMatchUserId.getId();
                        }
                        matchUserHouse.setMatchUserStockId(id3 + "");
                        matchUserHouse.setHouseId(matchUserHouseVO.getHouseId());
                        // List<CommunityHouseUser> users = communityHouseUserRepository.findByCommunityHouseIdAndStatusAndType(houseId, 1, 1);
                        // matchUserHouse.setMemberUserId(!users.isEmpty() ? users.get(0).getId() : null);
                        matchUserHouse.setLabel(matchUserHouseVO.getLabel());
                        matchUserHouse.setCompanyName(matchUserHouseVO.getCompanyName());
                        matchUserHouse.setSocialCreditNumber(matchUserHouseVO.getSocialCreditNumber());
                        matchUserHouse.setStartDate(matchUserHouseVO.getStartDate());
                        matchUserHouse.setEndDate(matchUserHouseVO.getEndDate());
                        matchUserHouse.setChargeMode(matchUserHouseVO.getChargeMode());
                        matchUserHouse.setCreateTime(new Date());
                        // 承租人和房屋关系表
                        matchUserHouseRepository.save(matchUserHouse);
                    }
                } else {
                    //	如果是产权单位或者物业机构合租也得自己添加承租人
                    MatchUserHouseVO matchUserHouseVO = saveOrEditVO.getMatchUserHouseVO();
                    if (matchUserHouseVO != null) {
                        List<UserDepartmentRef> byDepId = userDepartmentRefRepository.findByDepId(enterpriseId);
                        if (byDepId.size() > 0) {
                            String userId = byDepId.get(0).getUserId();
                            // 获取单位承租人机构用户信息
                            User byId = userRepository.findById(userId);
                            String id2 = byId.getId();
                            String name = byId.getName();
                            List<UserDepartmentRef> byUserId = userDepartmentRefRepository.findByUserId(id2);
                            // 获取机构名称
                            if (!byUserId.isEmpty()) {
                                Long depId = byUserId.get(0).getDepId();
                                Optional<Department> byId1 = departmentRepository.findById(depId);
                                String name1 = byId1.get().getName();
                                name = name1;
                            }
                            // 获取承租人库信息
                            MatchUser byMatchUserId = matchUserRepository.findByMatchUserId(id2);
                            if (byMatchUserId == null) {
                                // 新增承租人库
                                MatchUser matchUser = new MatchUser();
                                matchUser.setMatchUserId(id2);
                                matchUser.setName(name);
                                matchUser.setPhone(byId.getMobile());
                                matchUser.setDeleteStatus(false);
                                matchUser.setCraeteUserId(token.getId());
                                matchUser.setCreateTime(new Date());
                                matchUser.setLastUpdateTime(new Date());
                                matchUserRepository.save(matchUser);
                            }
                            //	获取承租人智能锁信息
                            // MatchUserLockAuthor byMatchUserStock = matchUserLockAuthorRepository.findByHouseId(matchUserHouseVO.getHouseId());
                            List<MatchUserLockAuthor> byMatchUserStockList = matchUserLockAuthorRepository.findByHouseId(matchUserHouseVO.getHouseId());
                            if (byMatchUserStockList.size() < 1) {
                                byMatchUserId = matchUserRepository.findByMatchUserId(id2);
                                Long id3 = null;
                                if (byMatchUserId != null) {
                                    id3 = byMatchUserId.getId();
                                }
                                MatchUserLockAuthor byMatchUserStock = new MatchUserLockAuthor();
                                byMatchUserStock.setCreateTime(new Date());
                                byMatchUserStock.setOperatorUserId(1l);
                                // 同时插入临时密码次数记录
                                // 生效年月
                                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");
                                byMatchUserStock.setEffectiveJulyDate(dateFormat.format(new Date()));
                                byMatchUserStock.setHouseId(matchUserHouseVO.getHouseId());
                                byMatchUserStock.setMatchUserStockId(id3 + "");
                                // 默认5次
                                byMatchUserStock.setAuthorNumber(5);
                                // 默认1天
                                byMatchUserStock.setPasswordValidity(1);
                                byMatchUserStock.setUseNumber(0);
                                byMatchUserStock.setLastUpdateTime(new Date());
                                matchUserLockAuthorRepository.save(byMatchUserStock);
                            }
                            // 先查一遍数据库中是否有该承租人和房屋的关系，根据房屋id查询，没有就更新
                            // 产权机构和物业机构 如果是合租下的房屋，不用机构自己添加承租人
                            List<House> byHousemateIdAndStatus = houseRepository.findByIdAndStatus(matchUserHouseVO.getHouseId(), 1);
                            if (byHousemateIdAndStatus.get(0).getHousemateId() == null) {
                                List<MatchUserHouse> byHouseList = matchUserHouseRepository.findByHouseId(matchUserHouseVO.getHouseId());
                                MatchUserHouse matchUserHouse = null;
                                if (byHouseList.size() < 1) {
                                    matchUserHouse = new MatchUserHouse();
                                    byMatchUserId = matchUserRepository.findByMatchUserId(id2);
                                    Long id3 = null;
                                    if (byMatchUserId != null) {
                                        id3 = byMatchUserId.getId();
                                    }
                                    matchUserHouse.setMatchUserStockId(id3 + "");
                                    matchUserHouse.setHouseId(matchUserHouseVO.getHouseId());
                                    // List<CommunityHouseUser> users = communityHouseUserRepository.findByCommunityHouseIdAndStatusAndType(houseId, 1, 1);
                                    // matchUserHouse.setMemberUserId(!users.isEmpty() ? users.get(0).getId() : null);
                                    matchUserHouse.setLabel(matchUserHouseVO.getLabel());
                                    matchUserHouse.setCompanyName(matchUserHouseVO.getCompanyName());
                                    matchUserHouse.setSocialCreditNumber(matchUserHouseVO.getSocialCreditNumber());
                                    matchUserHouse.setStartDate(matchUserHouseVO.getStartDate());
                                    matchUserHouse.setEndDate(matchUserHouseVO.getEndDate());
                                    matchUserHouse.setChargeMode(matchUserHouseVO.getChargeMode());
                                    matchUserHouse.setCreateTime(new Date());
                                    // 承租人和房屋关系表
                                    matchUserHouseRepository.save(matchUserHouse);
                                }
                            }

                        }
                    }
                }
                // 查询承租人库是否存在此承租人
                Optional<CommunityHouseUser> matchUserOpt = saveOrEditVO.getCommunityHouseUsers().stream()
                        .filter(i -> i.getType() == 1).findFirst();
                log.info("saveOrEdit matchUserOpt={}", JSON.toJSONString(matchUserOpt));
                CommunityHouseUser cmatchUser = null;
                if (matchUserOpt.isPresent()) {
                    cmatchUser = matchUserOpt.get();
                }
                //-------------------------------特殊关系(儿子、女儿)处理-----------------------------------
                // 编辑时由于特殊关系的手机号码增加了后缀，到时无法编辑保存，优化如下：
                // List<CommunityHouseUser> communityHouseUsers = saveOrEditVO.getCommunityHouseUsers();
                // List<Long> ids = saveOrEditVO.getCommunityHouseUsers().stream().filter(s -> s.getId() != null).map(t -> t.getId()).collect(Collectors.toList());
                // if(ids != null && !ids.isEmpty()){
                //	List<CommunityHouseUser> chuList = communityHouseUserRepository.findByIdIn(ids);
                //	for (CommunityHouseUser chu : chuList) {
                //		for (CommunityHouseUser vo : saveOrEditVO.getCommunityHouseUsers()) {
                //			if(vo.getId() != null && chu.getId().intValue() == vo.getId().intValue()){
                //				// 编辑时返回的数据，去掉后缀，保存时恢复原数据的后缀，而后继续后续逻辑处理(手机号码是不可编辑的，所以可以这样处理)
                //				if(chu.getMobile().contains("_")){
                //					vo.setMobile(chu.getMobile());
                //				}
                //
                //				// 特殊关系编辑时不能修改关系类型
                //				if(chu.getRelationTag() != null && vo.getRelationTag() != null && (chu.getRelationTag() == 3 || chu.getRelationTag() == 5) && vo.getRelationTag() != chu.getRelationTag()){
                //					return ResultBean.failedResultWithMsg("特殊关系(儿子、女儿)同住人，不能修改关系!");
                //				}
                //			}
                //		}
                //	}
                //}

               /* int count = 0;
                // 如果是编辑，保持后缀有序生成
                for (CommunityHouseUser vo : saveOrEditVO.getCommunityHouseUsers()) {
                    if (vo.getMobile().contains("_")) {
                        String suffixCount = vo.getMobile().substring(vo.getMobile().indexOf("_") + 1);
                        if (Integer.parseInt(suffixCount) > count) {
                            count = Integer.parseInt(suffixCount);
                        }
                    }
                }
                count++;*/
                // 如果是编辑，保持后缀有序生成
                for (CommunityHouseUser vo : saveOrEditVO.getCommunityHouseUsers()) {
                    if (vo.getMobile().contains("_")) {
                        String substring = vo.getMobile().substring(0, 11);
                        vo.setMobile(substring + "_" + count);
                        count++;
                    }
                }


                // 新增是否有手机号：1是 0否
                for (CommunityHouseUser communityHouseUser : saveOrEditVO.getCommunityHouseUsers()) {
                    if (communityHouseUser.getMobile().contains("_")) {
                        communityHouseUser.setMobileStatus(CommunityHouseUser.MOBILE_STATUS_NO);
                    } else {
                        communityHouseUser.setMobileStatus(CommunityHouseUser.MOBILE_STATUS_YES);
                    }
                }
                //---------------------------------------------------------------------------------------------

                // 验证成员之间手机号码与身份证是否重复
                // List<String> mobiles = saveOrEditVO.getCommunityHouseUsers().stream().map(mm -> mm.getMobile()).distinct().collect(Collectors.toList());
                // if(mobiles.size() < saveOrEditVO.getCommunityHouseUsers().size()){
                //	return ResultBean.failedResultWithMsg("成员手机号码不能重复");
                //}
                //
                // List<String> cardNumbers1 = saveOrEditVO.getCommunityHouseUsers().stream().filter(mm -> StringUtils.isNotBlank(mm.getCardNumber())).map(mm -> mm.getCardNumber()).collect(Collectors.toList());
                // List<String> cardNumbers2 = saveOrEditVO.getCommunityHouseUsers().stream().filter(mm -> StringUtils.isNotBlank(mm.getCardNumber())).map(mm -> mm.getCardNumber()).distinct().collect(Collectors.toList());
                // if(cardNumbers1.size() != cardNumbers2.size()){
                //	return ResultBean.failedResultWithMsg("成员身份证号码不能重复");
                //}

                // 查询需去重的手机号码
                // String mobileSql = "SELECT distinct tt.mobile FROM ("
                //		+ "SELECT hu.mobile, hu.card_number FROM saas_community_house_user hu WHERE hu.type = 2 AND hu.status = 1 "
                //		+ "UNION ALL "
                //		+ "SELECT hu.mobile, hu.card_number FROM saas_community_house_user hu LEFT JOIN m_match_user_house uh ON hu.community_house_id = uh.house_id "
                //		+ "WHERE uh.label = 1 AND hu.status = 1 ) tt";
                //
                //
                // List<CommunityHouseUser> matchUsers = jdbcTemplate.query(mobileSql, new BeanPropertyRowMapper<>(CommunityHouseUser.class));
                // Map<String, CommunityHouseUser> mobileMap = matchUsers.stream().collect(Collectors.toMap(CommunityHouseUser::getMobile, CommunityHouseUser -> CommunityHouseUser));

                // String cardSql = "SELECT distinct tt.card_number FROM ("
                //		+ "SELECT hu.mobile, hu.card_number FROM saas_community_house_user hu WHERE hu.type = 2 AND hu.status = 1 "
                //		+ "UNION ALL "
                //		+ "SELECT hu.mobile, hu.card_number FROM saas_community_house_user hu LEFT JOIN m_match_user_house uh ON hu.community_house_id = uh.house_id "
                //		+ "WHERE uh.label = 1 AND hu.status = 1 ) tt";
                // List<CommunityHouseUser> cardUsers = jdbcTemplate.query(cardSql, new BeanPropertyRowMapper<>(CommunityHouseUser.class));
                // Map<String, CommunityHouseUser> cardMap = cardUsers.stream().filter(ff -> StringUtils.isNotBlank(ff.getCardNumber())).collect(Collectors.toMap(CommunityHouseUser::getCardNumber, CommunityHouseUser -> CommunityHouseUser));
                //
                ////获取房屋id,设置房屋为已出租状态
                // String voHouseId = muhVO.getHouseId();
                // Optional<House> byId1 = houseRepository.findById(voHouseId);
                // byId1.get().setLeaseStatus(1);
                ////获取房屋类型：性质:1公租房、2保障房、3出租房、4自用房、5单位宿舍
                // Integer houseNature = byId1.get().getHouseNature();
                /*//公租房需要去重
                if (houseNature == 1 || houseNature == 2) {
                    for (CommunityHouseUser communityHouseUser : saveOrEditVO.getCommunityHouseUsers()) {
                        // 新增
                        if (communityHouseUser.getId() == null) {
                            List<CommunityHouseUser> entity = communityHouseUserRepository.findByMobileAndStatus(communityHouseUser.getMobile(), 1);
                            //if (mobileMap.get(communityHouseUser.getMobile()) != null) {
                            //	return ResultBean
                            //			.failedResultWithMsg("手机：" + communityHouseUser.getMobile() + "，已绑定其它房产，不能重复添加");
                            //}

                            //if(StringUtils.isNoneBlank(communityHouseUser.getCardNumber())){
                            //	//List<CommunityHouseUser> entity2 = communityHouseUserRepository.findByCardNumberAndStatus(communityHouseUser.getCardNumber(), 1);
                            //	if (cardMap.get(communityHouseUser.getCardNumber()) != null) {
                            //		return ResultBean.failedResultWithMsg(
                            //				"身份证：" + communityHouseUser.getCardNumber() + "，已绑定其它房产，不能重复添加");
                            //	}
                            //}
                            //如果是在出租房住的，还能再进保障房入住
                            if (!entity.isEmpty()) {
                                for (CommunityHouseUser houseUser : entity) {
                                    String communityHouseId = houseUser.getCommunityHouseId();
                                    List<House> byIdAndStatus = houseRepository.findByIdAndStatus(communityHouseId, 1);
                                    if (!byIdAndStatus.isEmpty()) {
                                        House house = byIdAndStatus.get(0);
                                        Integer houseNature1 = house.getHouseNature();
                                        if (houseNature1 == 1 || houseNature1 ==2) {
                                                return ResultBean.failedResultWithMsg("手机：" + communityHouseUser.getMobile() + "，已绑定其它房产，不能重复添加");
                                        }
                                    }
                                }
                            }

                        }

                        // 编辑
                        if (communityHouseUser.getId() != null) {
                            Optional<CommunityHouseUser> houseUserOptional = communityHouseUserRepository
                                    .findById(communityHouseUser.getId());
                            CommunityHouseUser houseUser = houseUserOptional.get();
                            if (!houseUser.getMobile().equals(communityHouseUser.getMobile())) {
                                //List<CommunityHouseUser> entity = communityHouseUserRepository.findByMobileAndStatus(communityHouseUser.getMobile(), 1);
                                if (mobileMap.get(communityHouseUser.getMobile()) != null) {
                                    return ResultBean.failedResultWithMsg(
                                            "手机：" + communityHouseUser.getMobile() + "，已绑定其它房产，不能重复添加");
                                }
                            }

                            // 验证身份证
                            if (StringUtils.isNotBlank(communityHouseUser.getCardNumber()) && !communityHouseUser.getCardNumber().equals(houseUser.getCardNumber())) {
                                //List<CommunityHouseUser> entity2 = communityHouseUserRepository.findByCardNumberAndStatus(communityHouseUser.getCardNumber(), 1);
                                if (cardMap.get(communityHouseUser.getCardNumber()) != null) {
                                    return ResultBean.failedResultWithMsg(
                                            "身份证：" + communityHouseUser.getCardNumber() + "，已绑定其它房产，不能重复添加");
                                }
                            }
                        }
                    }
                }*/
                // 保存设置房屋为已出租状态
                byId2.get().setLeaseStatus(4);
                houseRepository.save(byId2.get());
                // 新增租户信息
                for (CommunityHouseUser communityHouseUser : saveOrEditVO.getCommunityHouseUsers()) {
                    // 新增
                    if (communityHouseUser.getId() == null) {
                        // 新增同住人是否给与查看账单标识
                        Integer accountStatus = communityHouseUser.getAccountStatus();
                        if (accountStatus != null) {
                            if (accountStatus == 1) {
                                communityHouseUser.setAccountStatus(1);
                            } else {
                                communityHouseUser.setAccountStatus(2);
                            }
                        }
                        // 查看新增的用户是否已经实名认证了，如果已经实名，就用用户实名认证的名字存储
                        String mobile = communityHouseUser.getMobile();
                        AppUser byPhoneAndStatus = appUserRepository.findByPhoneAndStatusAndCertificationStatusAndType(mobile, 1, 1, UserLoginTypeEnum.CONSUMER.getValue());
                        if (byPhoneAndStatus != null) {
                            String name = byPhoneAndStatus.getName();
                            communityHouseUser.setName(name);
                        }
                        communityHouseUser.setStatus(1);
                        communityHouseUser.setOperatorId(token.getId());
                        communityHouseUser.setOperatorTime(date);
                    }

                    // 租户与房屋管理员区分
                    if (communityHouseUser.getType() != null && communityHouseUser.getType() != 3) {
                        // 查询租户对应的账户信息
                        AppUser appUser = appUserRepository.findByPhoneAndTypeAndStatus(communityHouseUser.getMobile(), UserLoginTypeEnum.CONSUMER.getValue(), 1);
                        if (communityHouseUser.getType() == 1) {
                            if (ObjectUtil.isNotEmpty(appUser) || ObjectUtil.isNotEmpty(newAppUser)) {
                                communityHouseUser.setUserId(ObjectUtil.isNotEmpty(appUser) ? appUser.getId() : newAppUser.getId());
                            }
                        } else {
                            if (appUser != null) {
                                communityHouseUser.setUserId(appUser.getId());
                            } else {
                                User user = userRepository.findByMobile(communityHouseUser.getMobile());
                                if (user != null) {
                                    communityHouseUser.setUserId(user.getId());
                                }
                            }
                        }
                        communityHouseUser.setUserType(1);

                    } else {
                        // 企业管理员的账户信息
                        User user = userRepository.findByMobile(communityHouseUser.getMobile());
                        if (user != null) {
                            communityHouseUser.setUserId(user.getId());
                        }
                        communityHouseUser.setUserType(2);
                    }
                    communityHouseUser.setChangeLabel(1);
                }
                String[] houseIds = newHouse.getId().split(",");
                MatchUser mUser = null;
                // 承租人库不存在该承租人
                if (ObjectUtil.isNotEmpty(cmatchUser)) {
                    AppUser appUser = appUserRepository.findByPhoneAndTypeAndStatus(cmatchUser.getMobile(), UserLoginTypeEnum.CONSUMER.getValue(), 1);
                    String matchUserId = appUser != null ? appUser.getId() : newAppUser.getId();
                    mUser = matchUserRepository.findByMatchUserId(matchUserId);
                    if (ObjectUtil.isEmpty(mUser)) {
                        // 新增承租人库
                        MatchUser matchUser = new MatchUser();
                        matchUser.setMatchUserId(appUser != null ? appUser.getId() : newAppUser.getId());
                        matchUser.setName(appUser != null ? appUser.getName() : cmatchUser.getName());
                        matchUser.setPhone(cmatchUser.getMobile());
                        matchUser.setDeleteStatus(false);
                        matchUser.setCraeteUserId(token.getId());
                        matchUser.setCreateTime(new Date());
                        matchUser.setLastUpdateTime(new Date());
                        mUser = matchUserRepository.save(matchUser);
                    }


                }

                List<MatchUserLockAuthor> uList = new ArrayList<>();
                for (int i = 0; i < houseIds.length; i++) {
                    // 查询是否存在设置记录
                    // MatchUserLockAuthor byMatchUserStock = matchUserLockAuthorRepository.findByHouseId(houseIds[i]);
                    List<MatchUserLockAuthor> byMatchUserStockList = matchUserLockAuthorRepository.findByHouseId(houseIds[i]);
                    if (byMatchUserStockList.size() < 1) {
                        MatchUserLockAuthor byMatchUserStock = new MatchUserLockAuthor();
                        byMatchUserStock.setCreateTime(new Date());
                        byMatchUserStock.setOperatorUserId(1l);
                        // 同时插入临时密码次数记录
                        // 生效年月
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");
                        byMatchUserStock.setEffectiveJulyDate(dateFormat.format(new Date()));
                        byMatchUserStock.setHouseId(houseIds[i]);
                        // 默认5次
                        byMatchUserStock.setAuthorNumber(5);
                        // 默认1天
                        byMatchUserStock.setPasswordValidity(1);
                        byMatchUserStock.setUseNumber(0);

                        if (cmatchUser == null && mUser != null && mUser.getId() != null) {
                            byMatchUserStock.setMatchUserStockId(mUser.getId() + "");
                        } else if (cmatchUser != null) {
                            byMatchUserStock.setMatchUserStockId(cmatchUser.getMatchId() + "");
                        }

                        byMatchUserStock.setLastUpdateTime(new Date());
                        uList.add(byMatchUserStock);
                    }
                }
                matchUserLockAuthorRepository.saveAll(uList);

                List<BacklogItemVo> backlogItemList = new ArrayList<>();

                for (String houseId : houseIds) {
                    // 先查一遍数据库中是否有该承租人和房屋的关系，根据房屋id查询，有就更新
                    List<MatchUserHouse> byHouseList = matchUserHouseRepository.findByHouseId(houseId);
                    MatchUserHouse matchUserHouse = null;
                    MatchUserHouseVO matchUserHouseVO = saveOrEditVO.getMatchUserHouseVO();
                    if (byHouseList == null || byHouseList.isEmpty()) {
                        matchUserHouse = new MatchUserHouse();
                    } else {
                        // 更新
                        matchUserHouse = byHouseList.get(0);
                    }

                    if (cmatchUser == null && mUser == null) {
                        break;
                    }

                    if (cmatchUser.getMatchId() == null && mUser != null && mUser.getId() != null) {
                        matchUserHouse.setMatchUserStockId(mUser.getId() + "");
                    } else if (cmatchUser.getMatchId() != null) {
                        matchUserHouse.setMatchUserStockId(cmatchUser.getMatchId() + "");
                    }

                    matchUserHouse.setHouseId(houseId);
                    // List<CommunityHouseUser> users = communityHouseUserRepository.findByCommunityHouseIdAndStatusAndType(houseId, 1, 1);
                    // matchUserHouse.setMemberUserId(!users.isEmpty() ? users.get(0).getId() : null);
                    matchUserHouse.setLabel(matchUserHouseVO.getLabel());
                    matchUserHouse.setCompanyName(matchUserHouseVO.getCompanyName());
                    matchUserHouse.setSocialCreditNumber(matchUserHouseVO.getSocialCreditNumber());
                    matchUserHouse.setStartDate(matchUserHouseVO.getStartDate());
                    matchUserHouse.setEndDate(matchUserHouseVO.getEndDate());
                    matchUserHouse.setChargeMode(matchUserHouseVO.getChargeMode());
                    matchUserHouse.setCreateTime(new Date());
                    // 承租人和房屋关系表
                    matchUserHouseRepository.save(matchUserHouse);
                }

                for (String houseId : houseIds) {
                    Map<String, Long> orgId = new HashMap<>();

                    String residenceCommunityId = null;
                    Optional<House> byId = houseRepository.findById(houseId);

                    if (byId.isPresent()) {
                        House house = byId.get();
                        residenceCommunityId = house.getResidenceCommunityId();
                        orgId.put("orgId", house.getOrgId());
                        orgId.put("housePropertyId", house.getHousePropertyId());
                    }
                    // 整租房产添加成员如果有绑定智能锁的情况下添加智能锁信息
                    List<SmartLock> lockList = smartLockRepository.findByHouseIdAndStatus(houseId, 1);
                    // 合租房产添加成员如果有绑定智能锁的情况下添加智能锁信息
                    List<House> byIdAndStatus = houseRepository.findByIdAndStatus(houseId, 1);
                    String housemateId1 = null;
                    if (byIdAndStatus.size() > 0) {
                        housemateId1 = byIdAndStatus.get(0).getHousemateId();
                    }

                    // 获取合租房产的智能锁信息
                    List<SmartLock> lockSubHouseList = smartLockRepository.findByHouseIdAndStatus(housemateId1, 1);
                    if (!lockList.isEmpty() || !lockSubHouseList.isEmpty()) {// 已安装锁
                        SmartLock smartLock = lockList.size() > 0 ? lockList.get(0) : lockSubHouseList.get(0);
                        Long lockId = lockList.size() > 0 ? lockList.get(0).getId() : lockSubHouseList.get(0).getId();

                        // 租户id
                        List<CommunityHouseUser> tenantList = saveOrEditVO.getCommunityHouseUsers().stream()
                                .filter(c -> c.getType() == 1).collect(Collectors.toList());
                        String matchUserId = null;
                        String matchUserName = null;
                        if (!tenantList.isEmpty()) {
                            matchUserId = tenantList.get(0).getUserId();
                            matchUserName = tenantList.get(0).getName();

                            String mobile = tenantList.get(0).getMobile();
                            // 查看新增的用户是否已经实名认证了，如果已经实名，就用用户实名认证的名字存储
                            AppUser byPhoneAndStatus = appUserRepository.findByPhoneAndStatusAndCertificationStatusAndType(mobile, 1, 1, UserLoginTypeEnum.CONSUMER.getValue());
                            if (ObjectUtil.isNotEmpty(byPhoneAndStatus)) {
                                matchUserName = byPhoneAndStatus.getName();
                            }
                        }

                        // 更新锁承租人id、姓名
                        smartLock.setMatchUserId(matchUserId);
                        smartLock.setMatchUserName(matchUserName);
                        smartLockRepository.save(smartLock);
                        for (CommunityHouseUser communityHouseUser : saveOrEditVO.getCommunityHouseUsers()) {
                            Long id = communityHouseUser.getId();
                            String name = communityHouseUser.getName();
                            String mobile = communityHouseUser.getMobile();
                            if (id == null) {// 新增
                                // 新增添加成员的时候，如果用户已经实名了，需要存在用户的身份证号和人脸照 xiaolong20230330
                                AppUser byPhoneAndStatusAndCertificationStatus = appUserRepository.findByPhoneAndStatusAndCertificationStatusAndType(mobile, 1, 1, UserLoginTypeEnum.CONSUMER.getValue());
                                if (byPhoneAndStatusAndCertificationStatus != null) {
                                    String facePic = byPhoneAndStatusAndCertificationStatus.getFacePic();
                                    String cardNumber = byPhoneAndStatusAndCertificationStatus.getCardNumber();
                                    communityHouseUser.setHumanFaceImage(facePic);
                                    communityHouseUser.setCardNumber(cardNumber);
                                }
                                // 修改为新增的房屋id
                                communityHouseUser.setCommunityHouseId(houseId);
                                CommunityHouseUser save = communityHouseUserRepository.save(communityHouseUser);
                                // 产生待办事项, type: 1新增同住人  2 新增承租人 3 删除同住人  4 删除承租人
                                Integer type = save.getType() == 1 ? 2 : 1;
                                BacklogItemVo backlogItemVo = new BacklogItemVo();
                                backlogItemVo.setCommunityHouseId(houseId);// 房产id
                                backlogItemVo.setUserOrgId(token.getEnterpriseId());// 个人组织id
                                backlogItemVo.setName(communityHouseUser.getName());// 人员名称
                                backlogItemVo.setOperatorId(token.getId());// 操作人id
                                backlogItemVo.setId(save.getId());// 房产成员信息登记表明细表id   saas_community_house_user
                                backlogItemVo.setType(type);// 1新增同住人  2 新增承租人 3 删除同住人  4 删除承租人
                                backlogItemVo.setPhone(save.getMobile());// 手机号
                                backlogItemList.add(backlogItemVo);

                                backlogItem(houseId, token.getEnterpriseId(), communityHouseUser.getName(), token.getId(), save.getId(), type);

                                SmartLockAuth auth = new SmartLockAuth();
                                auth.setLockId(lockId);
                                auth.setHouseId(smartLock.getHouseId());
                                auth.setBindType(0);// 单位
                                auth.setMatchUserId(matchUserId);
                                auth.setAuthorUserId(communityHouseUser.getUserId());
                                if (communityHouseUser.getType() == 1) {
                                    auth.setUserType(1);
                                } else if (communityHouseUser.getType() == 2) {
                                    auth.setUserType(2);
                                } else if (communityHouseUser.getType() == 3) {
                                    auth.setUserType(3);
                                } else {
                                    auth.setUserType(4);
                                }
                                auth.setUserName(name);
                                auth.setMobile(mobile);

                                if (smartLock.getMechineStatus() == 2) {
                                    auth.setPwdStatus(2);
                                    auth.setFingerprintStatus(2);
                                    auth.setCardStatus(2);
                                    auth.setCpuStatus(2);
                                    auth.setBleStatus(2);
                                    auth.setFaceStatus(2);
                                } else {
                                    auth.setPwdStatus(0);
                                    auth.setFingerprintStatus(0);
                                    auth.setCardStatus(0);
                                    auth.setCpuStatus(0);
                                    auth.setBleStatus(0);
                                    auth.setFaceStatus(0);
                                }
                                auth.setRelationTag(communityHouseUser.getRelationTag());
                                auth.setCreateTime(date);
                                auth.setCommunityUserId(save.getId());
                                // 新增合租房屋子房屋Id
                                auth.setSubHouseId(communityHouseUser.getCommunityHouseId());
                                // 新增房屋号
                                List<House> byIdAndStatus1 = houseRepository.findByIdAndStatus(communityHouseUser.getCommunityHouseId(), 1);
                                String num = null;
                                if (byIdAndStatus1.size() > 0) {
                                    num = byIdAndStatus1.get(0).getRoomNumber();
                                }
                                auth.setRoomNumber(num);
                                smartLockAuthRepository.save(auth);

                                Long orgId1 = orgId.get("orgId");
                                Long housePropertyId1 = orgId.get("housePropertyId");
                                ArrayList<Long> orgIds = new ArrayList<>();
                                orgIds.add(orgId1);
                                orgIds.add(housePropertyId1);
                                // 产生承租人余额账户
                                /*if (communityHouseUser.getType() == 1) {
                                    List<HouseRemainingRelation> remRelationList = houseRemainingRelationRepository.findByOrgIdInAndHouseId(orgIds, houseId);
                                    if (!remRelationList.isEmpty()){
                                        List<Long> remId = remRelationList.stream().map(HouseRemainingRelation::getRemainingId).collect(Collectors.toList());
                                        List<HouseRemaining> houseRemainings = houseRemainingRepository.findByIdIn(remId);
                                        if (!houseRemainings.isEmpty()){
                                            houseRemainings.forEach(m-> m.setStatus(RemainingStatusEnum.RENUNCIATION.getValue()));
                                        }
                                        houseRemainingRelationRepository.deleteAll(remRelationList);
                                    }


                                    if (orgId1 != null ){
                                        HouseRemaining rem = new HouseRemaining();
                                        rem.setRemainingType(1);
                                        rem.setType(muhVO.getLabel());
                                        rem.setHouseId(houseId);
                                        rem.setOrgId(orgId1);
                                        rem.setBalanceFee(0);
                                        rem.setCashPledge(0);
                                        rem.setMatchUserId(save.getUserId());
                                        rem.setLastUpdateTime(date);
                                        rem.setCreateTime(date);
                                        rem.setStatus(RemainingStatusEnum.NORMAL.getValue());
                                        HouseRemaining remSave = houseRemainingRepository.save(rem);


                                        HouseRemainingRelation remRelation = new HouseRemainingRelation();
                                        remRelation.setHouseId(houseId);
                                        remRelation.setRemainingId(remSave.getId());
                                        remRelation.setCreateTime(date);
                                        remRelation.setOrgId(orgId1);
                                        houseRemainingRelationRepository.save(remRelation);
                                    }
                                    if (housePropertyId1 != null ){
                                        HouseRemaining rem = new HouseRemaining();
                                        rem.setRemainingType(2);
                                        rem.setType(muhVO.getLabel());
                                        rem.setHouseId(houseId);
                                        rem.setOrgId(housePropertyId1);
                                        rem.setBalanceFee(0);
                                        rem.setCashPledge(0);
                                        rem.setMatchUserId(save.getUserId());
                                        rem.setLastUpdateTime(date);
                                        rem.setCreateTime(date);
                                        rem.setStatus(RemainingStatusEnum.NORMAL.getValue());
                                        HouseRemaining remSave = houseRemainingRepository.save(rem);


                                        HouseRemainingRelation remRelation = new HouseRemainingRelation();
                                        remRelation.setHouseId(houseId);
                                        remRelation.setRemainingId(remSave.getId());
                                        remRelation.setCreateTime(date);
                                        remRelation.setOrgId(housePropertyId1);
                                        houseRemainingRelationRepository.save(remRelation);
                                    }
                                }*/

                                House house2 = houseRepository.findById(houseId).get();
                                List<CommunityHouseUser> houseUserList = communityHouseUserRepository.findByCommunityHouseIdAndStatus(house2.getId(), 1);
                                if (houseUserList.size() == 1 && !house2.getHouseNature().equals(7)) {
                                    //	获取合租房产下的房产承租人信息
                                    List<MatchUserHouse> byHouseId = matchUserHouseRepository.findByHouseId(communityHouseUser.getCommunityHouseId());
                                    if (!byHouseId.isEmpty()) {
                                        String matchUserStockId = byHouseId.get(0).getMatchUserStockId();
                                        //	根据承租人和房产的承租人id查询承认人表的房产承租人id
                                        Optional<MatchUser> matchUserRepositoryById = matchUserRepository.findById(Long.parseLong(matchUserStockId));
                                        if (matchUserRepositoryById.isPresent()) {
                                            // 产权下的用户承租人id
                                            MatchUser byMatchUserId = matchUserRepositoryById.get();
                                            // 产权下的用户承租人id
                                            String matchUserId1 = byMatchUserId.getMatchUserId();
                                            List<HouseRemainingRelation> remRelationList = houseRemainingRelationRepository.findByOrgIdInAndHouseId(orgIds, houseId);

                                            if (remRelationList.isEmpty()) {
                                                if (orgId1 != null) {
                                                    HouseRemaining rem = new HouseRemaining();
                                                    rem.setRemainingType(1);
                                                    rem.setType(muhVO.getLabel());
                                                    rem.setHouseId(houseId);
                                                    rem.setOrgId(orgId1);
                                                    rem.setBalanceFee(0);
                                                    rem.setCashPledge(0);
                                                    rem.setMatchUserId(matchUserId1);
                                                    rem.setLastUpdateTime(date);
                                                    rem.setCreateTime(date);
                                                    rem.setStatus(RemainingStatusEnum.NORMAL.getValue());
                                                    HouseRemaining remSave = houseRemainingRepository.save(rem);


                                                    HouseRemainingRelation remRelation = new HouseRemainingRelation();
                                                    remRelation.setHouseId(houseId);
                                                    remRelation.setRemainingId(remSave.getId());
                                                    remRelation.setCreateTime(date);
                                                    remRelation.setOrgId(orgId1);
                                                    houseRemainingRelationRepository.save(remRelation);
                                                }
                                                if (housePropertyId1 != null && !orgId1.equals(housePropertyId1)) {

                                                    HouseRemaining rem = new HouseRemaining();
                                                    rem.setRemainingType(2);
                                                    rem.setType(muhVO.getLabel());
                                                    rem.setHouseId(houseId);
                                                    rem.setOrgId(housePropertyId1);
                                                    rem.setBalanceFee(0);
                                                    rem.setCashPledge(0);
                                                    rem.setMatchUserId(matchUserId1);
                                                    rem.setLastUpdateTime(date);
                                                    rem.setCreateTime(date);
                                                    rem.setStatus(RemainingStatusEnum.NORMAL.getValue());
                                                    HouseRemaining remSave = houseRemainingRepository.save(rem);


                                                    HouseRemainingRelation remRelation = new HouseRemainingRelation();
                                                    remRelation.setHouseId(houseId);
                                                    remRelation.setRemainingId(remSave.getId());
                                                    remRelation.setCreateTime(date);
                                                    remRelation.setOrgId(housePropertyId1);
                                                    houseRemainingRelationRepository.save(remRelation);
                                                }
                                            }
                                            if (muhVO.getLabel() == 2) {
                                                List<DepartmentRemainingRef> depRemainingRef = departmentRemainingRefRepository.findByDepIdAndHouseId(muhVO.getId(), houseId);
                                                // 账户不存在
                                                if (depRemainingRef.isEmpty()) {
                                                    if (orgId1 != null) {
                                                        DepartmentRemaining depRem = departmentRemainingRepository.findByDepIdAndOrgId(muhVO.getId(), orgId1);
                                                        if (depRem == null) {
                                                            DepartmentRemaining departmentRemaining = new DepartmentRemaining();
                                                            departmentRemaining.setDepId(muhVO.getId());
                                                            departmentRemaining.setDepName(muhVO.getCompanyName());
                                                            departmentRemaining.setHouseId(houseId);
                                                            departmentRemaining.setOrgId(orgId1);
                                                            departmentRemaining.setBalanceFee(0);
                                                            departmentRemaining.setCashPledge(0);
                                                            departmentRemaining.setLastUpdateTime(date);
                                                            departmentRemaining.setCreateTime(date);
                                                            departmentRemaining.setStatus(1);
                                                            depRem = departmentRemainingRepository.save(departmentRemaining);
                                                        }

                                                        DepartmentRemainingRef remainingRef = new DepartmentRemainingRef();
                                                        remainingRef.setDepId(muhVO.getId());
                                                        remainingRef.setDepName(muhVO.getCompanyName());
                                                        remainingRef.setOrgId(orgId1);
                                                        remainingRef.setHouseId(houseId);
                                                        remainingRef.setRemainingId(depRem.getId());
                                                        remainingRef.setCreateTime(date);
                                                        remainingRef.setRentWithholdStatus(1);
                                                        remainingRef.setElseWithholdStatus(1);
                                                        departmentRemainingRefRepository.save(remainingRef);
                                                    }
                                                    if (housePropertyId1 != null && !orgId1.equals(housePropertyId1)) {
                                                        DepartmentRemaining depRem = departmentRemainingRepository.findByDepIdAndOrgId(muhVO.getId(), housePropertyId1);
                                                        if (depRem == null) {
                                                            DepartmentRemaining departmentRemaining = new DepartmentRemaining();
                                                            departmentRemaining.setDepId(muhVO.getId());
                                                            departmentRemaining.setDepName(muhVO.getCompanyName());
                                                            departmentRemaining.setHouseId(houseId);
                                                            departmentRemaining.setOrgId(housePropertyId1);
                                                            departmentRemaining.setBalanceFee(0);
                                                            departmentRemaining.setCashPledge(0);
                                                            departmentRemaining.setLastUpdateTime(date);
                                                            departmentRemaining.setCreateTime(date);
                                                            departmentRemaining.setStatus(1);
                                                            depRem = departmentRemainingRepository.save(departmentRemaining);
                                                        }
                                                        DepartmentRemainingRef remainingRef = new DepartmentRemainingRef();
                                                        remainingRef.setDepId(muhVO.getId());
                                                        remainingRef.setDepName(muhVO.getCompanyName());
                                                        remainingRef.setOrgId(housePropertyId1);
                                                        remainingRef.setHouseId(houseId);
                                                        remainingRef.setRemainingId(depRem.getId());
                                                        remainingRef.setCreateTime(date);
                                                        remainingRef.setRentWithholdStatus(1);
                                                        remainingRef.setElseWithholdStatus(1);
                                                        departmentRemainingRefRepository.save(remainingRef);
                                                    }
                                                }
                                            }

                                        }
                                    }
                                }


                                //	新增流动人员数据
                                //	类型：1租户 2成员 3房屋管理员 4房管员 (3房屋管理员和4房管员不用记录)
                                if (communityHouseUser.getType() == 1 || communityHouseUser.getType() == 2) {
                                    UserFloatingPopulationRecord record = new UserFloatingPopulationRecord();
                                    record.setUserId(communityHouseUser.getUserId());
                                    record.setUserPhone(communityHouseUser.getMobile());
                                    record.setUserName(communityHouseUser.getName());
                                    record.setHouseId(communityHouseUser.getCommunityHouseId());
                                    Optional<House> house1 = houseRepository.findById(communityHouseUser.getCommunityHouseId());
                                    House house = house1.get();
                                    record.setOrgId(house.getOrgId());
                                    record.setType(UserFloatingPopulationRecord.RECORD_TYPE_CHECK_IN);
                                    record.setCreateBy(token.getId());
                                    record.setCreateTime(new Date());
                                    userFloatingPopulationRecordService.insertUserFloatingPopulationRecord(record);
                                }
                            }

                            if (id != null) {// 编辑
                                // 首先查询数据库，如果数据库中的数据不为null或者""，再进入方法
                                // 判断如果humanFaceImage 为 null或者为""，就调用oss中删除文件的操作
                                if (StringUtils.isBlank(communityHouseUser.getHumanFaceImage())) {
                                    // 根据userId先查到数据
                                    List<CommunityHouseUser> byUserIdAndStatus = communityHouseUserRepository
                                            .findByIdAndStatus(communityHouseUser.getId(), 1);
                                    byUserIdAndStatus.forEach(item -> {
                                        if (StringUtils.isNotBlank(item.getHumanFaceImage())) {
                                            ossService.deleteObject(null, item.getHumanFaceImage());
                                        }
                                    });
                                }
                                String humanFaceImage = communityHouseUser.getHumanFaceImage();
                                if (humanFaceImage != null) {
                                    humanFaceImage = humanFaceImage.replace(ossBucketUrl, "");
                                }
                                communityHouseUser.setHumanFaceImage(humanFaceImage);
                                communityHouseUserRepository.save(communityHouseUser);

                                SmartLockAuth auth = smartLockAuthRepository.findByCommunityUserId(id);
                                if (auth != null) {
                                    auth.setMatchUserId(matchUserId);
                                    auth.setAuthorUserId(communityHouseUser.getUserId());
                                    auth.setUserName(name);
                                    auth.setMobile(mobile);
                                    auth.setRelationTag(communityHouseUser.getRelationTag());
                                    if (communityHouseUser.getType() == 1) {
                                        auth.setUserType(1);
                                    } else if (communityHouseUser.getType() == 2) {
                                        auth.setUserType(2);
                                    } else if (communityHouseUser.getType() == 3) {
                                        auth.setUserType(3);// 房屋管理员
                                    } else {
                                        auth.setUserType(4);// 房管员
                                    }
                                    smartLockAuthRepository.save(auth);
                                }
                            }
                        }
                    } else {// 未安装锁
                        for (CommunityHouseUser communityHouseUser : saveOrEditVO.getCommunityHouseUsers()) {
                            CommunityHouseUser entity = new CommunityHouseUser();
                            communityHouseUser.setCommunityHouseId(houseId);
                            communityHouseUser.setCommunityId(residenceCommunityId);
                            // 区分编辑与新增
                            Long id = communityHouseUser.getId();
                            String humanFaceImage = communityHouseUser.getHumanFaceImage();
                            if (humanFaceImage != null) {
                                humanFaceImage = humanFaceImage.replace(ossBucketUrl, "");
                            }
                            communityHouseUser.setHumanFaceImage(humanFaceImage);
                            BeanUtils.copyProperties(communityHouseUser, entity);
                            // 新增添加成员的时候，如果用户已经实名了，需要存在用户的身份证号和人脸照 xiaolong20230330
                            String mobile = communityHouseUser.getMobile();
                            AppUser byPhoneAndStatusAndCertificationStatus = appUserRepository.findByPhoneAndStatusAndCertificationStatusAndType(mobile, 1, 1, UserLoginTypeEnum.CONSUMER.getValue());
                            if (byPhoneAndStatusAndCertificationStatus != null) {
                                String facePic = byPhoneAndStatusAndCertificationStatus.getFacePic();
                                String cardNumber = byPhoneAndStatusAndCertificationStatus.getCardNumber();
                                entity.setHumanFaceImage(facePic);
                                entity.setCardNumber(cardNumber);
                            }
                            communityHouseUserRepository.save(entity);


                            if (id == null) {
                                Integer type = entity.getType() == 1 ? 2 : 1;
                                BacklogItemVo backlogItemVo = new BacklogItemVo();
                                backlogItemVo.setCommunityHouseId(houseId);// 房产id
                                backlogItemVo.setUserOrgId(token.getEnterpriseId());// 个人组织id
                                backlogItemVo.setName(communityHouseUser.getName());// 人员名称
                                backlogItemVo.setOperatorId(token.getId());// 操作人id
                                backlogItemVo.setId(entity.getId());// 房产成员信息登记表明细表id   saas_community_house_user
                                backlogItemVo.setType(type);// 1新增同住人  2 新增承租人 3 删除同住人  4 删除承租人
                                backlogItemVo.setPhone(entity.getMobile());// 手机号
                                backlogItemList.add(backlogItemVo);

                                // 产生待办事项
                                backlogItem(houseId, token.getEnterpriseId(), communityHouseUser.getName(), token.getId(),
                                        entity.getId(), type);
                                Long orgId1 = orgId.get("orgId");
                                Long housePropertyId1 = orgId.get("housePropertyId");
                                ArrayList<Long> orgIds = new ArrayList<>();
                                orgIds.add(orgId1);
                                orgIds.add(housePropertyId1);
                                // 产生承租人余额账户
                                /*if (communityHouseUser.getType() == 1) {
                                    List<HouseRemainingRelation> remRelationList = houseRemainingRelationRepository.findByOrgIdInAndHouseId(orgIds, houseId);
                                    if (!remRelationList.isEmpty()){
                                        List<Long> remId = remRelationList.stream().map(HouseRemainingRelation::getRemainingId).collect(Collectors.toList());
                                        List<HouseRemaining> houseRemainings = houseRemainingRepository.findByIdIn(remId);
                                        if (!houseRemainings.isEmpty()){
                                            houseRemainings.forEach(m-> m.setStatus(RemainingStatusEnum.DEL.getValue()));
                                        }
                                        houseRemainingRelationRepository.deleteAll(remRelationList);
                                    }


                                    if (orgId1 != null ){
                                        HouseRemaining rem = new HouseRemaining();
                                        rem.setRemainingType(1);
                                        rem.setType(muhVO.getLabel());
                                        rem.setHouseId(houseId);
                                        rem.setOrgId(orgId1);
                                        rem.setBalanceFee(0);
                                        rem.setCashPledge(0);
                                        rem.setMatchUserId(communityHouseUser.getUserId());
                                        rem.setLastUpdateTime(date);
                                        rem.setCreateTime(date);
                                        rem.setStatus(RemainingStatusEnum.NORMAL.getValue());
                                        HouseRemaining remSave = houseRemainingRepository.save(rem);


                                        HouseRemainingRelation remRelation = new HouseRemainingRelation();
                                        remRelation.setHouseId(houseId);
                                        remRelation.setRemainingId(remSave.getId());
                                        remRelation.setCreateTime(date);
                                        remRelation.setOrgId(orgId1);
                                        houseRemainingRelationRepository.save(remRelation);
                                    }
                                    if (housePropertyId1 != null ){
                                        HouseRemaining rem = new HouseRemaining();
                                        rem.setRemainingType(2);
                                        rem.setType(muhVO.getLabel());
                                        rem.setHouseId(houseId);
                                        rem.setOrgId(housePropertyId1);
                                        rem.setBalanceFee(0);
                                        rem.setCashPledge(0);
                                        rem.setMatchUserId(communityHouseUser.getUserId());
                                        rem.setLastUpdateTime(date);
                                        rem.setCreateTime(date);
                                        rem.setStatus(RemainingStatusEnum.NORMAL.getValue());
                                        HouseRemaining remSave = houseRemainingRepository.save(rem);


                                        HouseRemainingRelation remRelation = new HouseRemainingRelation();
                                        remRelation.setHouseId(houseId);
                                        remRelation.setRemainingId(remSave.getId());
                                        remRelation.setCreateTime(date);
                                        remRelation.setOrgId(housePropertyId1);
                                        houseRemainingRelationRepository.save(remRelation);
                                    }
                                }*/

                                House house = houseRepository.findById(houseId).get();
                                List<CommunityHouseUser> houseUserList = communityHouseUserRepository.findByCommunityHouseIdAndStatus(house.getId(), 1);
                                if (houseUserList.size() == 1 && !house.getHouseNature().equals(7)) {
                                    //	获取合租房产下的房产承租人信息
                                    List<MatchUserHouse> byHouseId = matchUserHouseRepository.findByHouseId(communityHouseUser.getCommunityHouseId());
                                    if (!byHouseId.isEmpty()) {
                                        String matchUserStockId = byHouseId.get(0).getMatchUserStockId();
                                        //	根据承租人和房产的承租人id查询承认人表的房产承租人id
                                        Optional<MatchUser> matchUserRepositoryById = matchUserRepository.findById(Long.parseLong(matchUserStockId));
                                        if (matchUserRepositoryById.isPresent()) {
                                            // 产权下的用户承租人id
                                            MatchUser byMatchUserId = matchUserRepositoryById.get();
                                            // 产权下的用户承租人id
                                            String matchUserId1 = byMatchUserId.getMatchUserId();
                                            List<HouseRemainingRelation> remRelationList = houseRemainingRelationRepository.findByOrgIdInAndHouseId(orgIds, houseId);

                                            if (remRelationList.isEmpty()) {
                                                if (orgId1 != null) {
                                                    HouseRemaining rem = new HouseRemaining();
                                                    rem.setRemainingType(1);
                                                    rem.setType(muhVO.getLabel());
                                                    rem.setHouseId(houseId);
                                                    rem.setOrgId(orgId1);
                                                    rem.setBalanceFee(0);
                                                    rem.setCashPledge(0);
                                                    rem.setMatchUserId(matchUserId1);
                                                    rem.setLastUpdateTime(date);
                                                    rem.setCreateTime(date);
                                                    rem.setStatus(RemainingStatusEnum.NORMAL.getValue());
                                                    HouseRemaining remSave = houseRemainingRepository.save(rem);


                                                    HouseRemainingRelation remRelation = new HouseRemainingRelation();
                                                    remRelation.setHouseId(houseId);
                                                    remRelation.setRemainingId(remSave.getId());
                                                    remRelation.setCreateTime(date);
                                                    remRelation.setOrgId(orgId1);
                                                    houseRemainingRelationRepository.save(remRelation);
                                                }
                                                if (housePropertyId1 != null && !orgId1.equals(housePropertyId1)) {

                                                    HouseRemaining rem = new HouseRemaining();
                                                    rem.setRemainingType(2);
                                                    rem.setType(muhVO.getLabel());
                                                    rem.setHouseId(houseId);
                                                    rem.setOrgId(housePropertyId1);
                                                    rem.setBalanceFee(0);
                                                    rem.setCashPledge(0);
                                                    rem.setMatchUserId(matchUserId1);
                                                    rem.setLastUpdateTime(date);
                                                    rem.setCreateTime(date);
                                                    rem.setStatus(RemainingStatusEnum.NORMAL.getValue());
                                                    HouseRemaining remSave = houseRemainingRepository.save(rem);


                                                    HouseRemainingRelation remRelation = new HouseRemainingRelation();
                                                    remRelation.setHouseId(houseId);
                                                    remRelation.setRemainingId(remSave.getId());
                                                    remRelation.setCreateTime(date);
                                                    remRelation.setOrgId(housePropertyId1);
                                                    houseRemainingRelationRepository.save(remRelation);
                                                }
                                            }
                                            if (muhVO.getLabel() == 2) {
                                                List<DepartmentRemainingRef> depRemainingRef = departmentRemainingRefRepository.findByDepIdAndHouseId(muhVO.getId(), houseId);
                                                // 账户不存在
                                                if (depRemainingRef.isEmpty()) {
                                                    if (orgId1 != null) {
                                                        DepartmentRemaining depRem = departmentRemainingRepository.findByDepIdAndOrgId(muhVO.getId(), orgId1);
                                                        if (depRem == null) {
                                                            DepartmentRemaining departmentRemaining = new DepartmentRemaining();
                                                            departmentRemaining.setDepId(muhVO.getId());
                                                            departmentRemaining.setDepName(muhVO.getCompanyName());
                                                            departmentRemaining.setHouseId(houseId);
                                                            departmentRemaining.setOrgId(orgId1);
                                                            departmentRemaining.setBalanceFee(0);
                                                            departmentRemaining.setCashPledge(0);
                                                            departmentRemaining.setLastUpdateTime(date);
                                                            departmentRemaining.setCreateTime(date);
                                                            departmentRemaining.setStatus(1);
                                                            depRem = departmentRemainingRepository.save(departmentRemaining);
                                                        }

                                                        DepartmentRemainingRef remainingRef = new DepartmentRemainingRef();
                                                        remainingRef.setDepId(muhVO.getId());
                                                        remainingRef.setDepName(muhVO.getCompanyName());
                                                        remainingRef.setOrgId(orgId1);
                                                        remainingRef.setHouseId(houseId);
                                                        remainingRef.setRemainingId(depRem.getId());
                                                        remainingRef.setCreateTime(date);
                                                        remainingRef.setRentWithholdStatus(1);
                                                        remainingRef.setElseWithholdStatus(1);
                                                        departmentRemainingRefRepository.save(remainingRef);
                                                    }
                                                    if (housePropertyId1 != null && !orgId1.equals(housePropertyId1)) {
                                                        DepartmentRemaining depRem = departmentRemainingRepository.findByDepIdAndOrgId(muhVO.getId(), housePropertyId1);
                                                        if (depRem == null) {
                                                            DepartmentRemaining departmentRemaining = new DepartmentRemaining();
                                                            departmentRemaining.setDepId(muhVO.getId());
                                                            departmentRemaining.setDepName(muhVO.getCompanyName());
                                                            departmentRemaining.setHouseId(houseId);
                                                            departmentRemaining.setOrgId(housePropertyId1);
                                                            departmentRemaining.setBalanceFee(0);
                                                            departmentRemaining.setCashPledge(0);
                                                            departmentRemaining.setLastUpdateTime(date);
                                                            departmentRemaining.setCreateTime(date);
                                                            departmentRemaining.setStatus(1);
                                                            depRem = departmentRemainingRepository.save(departmentRemaining);
                                                        }
                                                        DepartmentRemainingRef remainingRef = new DepartmentRemainingRef();
                                                        remainingRef.setDepId(muhVO.getId());
                                                        remainingRef.setDepName(muhVO.getCompanyName());
                                                        remainingRef.setOrgId(housePropertyId1);
                                                        remainingRef.setHouseId(houseId);
                                                        remainingRef.setRemainingId(depRem.getId());
                                                        remainingRef.setCreateTime(date);
                                                        remainingRef.setRentWithholdStatus(1);
                                                        remainingRef.setElseWithholdStatus(1);
                                                        departmentRemainingRefRepository.save(remainingRef);
                                                    }
                                                }
                                            }

                                        }
                                    }
                                }

                                //	新增流动人员数据
                                //	类型：1租户 2成员 3房屋管理员 4房管员 (3房屋管理员和4房管员不用记录)
                                if (communityHouseUser.getType() == 1 || communityHouseUser.getType() == 2) {
                                    UserFloatingPopulationRecord record = new UserFloatingPopulationRecord();
                                    record.setUserId(communityHouseUser.getUserId());
                                    record.setUserPhone(communityHouseUser.getMobile());
                                    record.setUserName(communityHouseUser.getName());
                                    record.setHouseId(communityHouseUser.getCommunityHouseId());
                                    record.setOrgId(house.getOrgId());
                                    record.setType(UserFloatingPopulationRecord.RECORD_TYPE_CHECK_IN);
                                    record.setCreateBy(token.getId());
                                    record.setCreateTime(new Date());
                                    userFloatingPopulationRecordService.insertUserFloatingPopulationRecord(record);
                                }
                            }


                        }
                    }
                }

                // 删除房屋管理员
                for (String houseId : houseIds) {
                    List<CommunityHouseUser> byCommunityHouseIdAndStatusAndType = communityHouseUserRepository.findByCommunityHouseIdAndStatusAndType(houseId, 1, 3);
                    if (byCommunityHouseIdAndStatusAndType != null && !byCommunityHouseIdAndStatusAndType.isEmpty()) {
                        deleteUserManager(accessToken, byCommunityHouseIdAndStatusAndType.get(0).getId());
                    }
                }
                // 删除合租产出中的房屋管理员
                MatchUserHouseVO matchUserHouseVO = saveOrEditVO.getMatchUserHouseVO();
                String houseId = matchUserHouseVO.getHouseId();
                List<CommunityHouseUser> byCommunityHouseIdAndStatusAndType = communityHouseUserRepository.findByCommunityHouseIdAndStatusAndType(houseId, 1, 3);
                if (byCommunityHouseIdAndStatusAndType != null && !byCommunityHouseIdAndStatusAndType.isEmpty()) {
                    deleteUserManager(accessToken, byCommunityHouseIdAndStatusAndType.get(0).getId());
                }
                // List<CommunityHouseUserVO> voList = new ArrayList<>();
                for (CommunityHouseUser communityHouseUser : saveOrEditVO.getCommunityHouseUsers()) {
                    CommunityHouseUserVO vo = convertToVO(communityHouseUser);
                    voList.add(vo);
                }
                // 待办事项
                // backlogItemList(backlogItemList);
                return ResultBean.successfulResult(voList);
            } else {

                // 特殊关系的同住人，如果手机号码与承租人相同，重置同住人手机号码，增加后缀（确保手机号字段唯一）
                int count = 0;
                for (CommunityHouseUser chu : saveOrEditVO.getCommunityHouseUsers()) {
                    for (CommunityHouseUser vo : saveOrEditVO.getCommunityHouseUsers()) {
                        Integer mobileStatus = vo.getMobileStatus();
                        if (mobileStatus == null) {
                            vo.setMobileStatus(1);
                        }
                        // 1妻子、2丈夫、3儿子、4儿媳、5女儿、6女婿、7父亲、8母亲、9同事、10哥哥、11嫂子、12姐姐、13姐夫、14弟弟、15弟媳、16妹妹、17妹夫、18其他亲属、19朋友、20非亲属
                        if (chu.getType() != null
                                && chu.getType() == 1
                                && chu.getMobile().equals(vo.getMobile())
                                && vo.getRelationTag() != null
                                && vo.getType() != null
                                && vo.getType() == 2
                                && (vo.getRelationTag() == 3 || vo.getRelationTag() == 5 || vo.getMobileStatus() == 0)) {
                            vo.setMobile(vo.getMobile() + "_" + count);
                            count++;
                        }
                    }
                }

                // 如果是编辑，保持后缀有序生成
                for (CommunityHouseUser vo : saveOrEditVO.getCommunityHouseUsers()) {
                    if (vo.getMobile().contains("_")) {
                        String substring = vo.getMobile().substring(0, 11);
                        vo.setMobile(substring + "_" + count);
                        count++;
                    }
                }


                // 新增是否有手机号：1是 0否
                for (CommunityHouseUser communityHouseUser : saveOrEditVO.getCommunityHouseUsers()) {
                    if (communityHouseUser.getMobile().contains("_")) {
                        communityHouseUser.setMobileStatus(CommunityHouseUser.MOBILE_STATUS_NO);
                    } else {
                        communityHouseUser.setMobileStatus(CommunityHouseUser.MOBILE_STATUS_YES);
                    }
                }


                // 查询需去重的手机号码
                String mobileSql = "SELECT distinct tt.mobile FROM ("
                        + "SELECT hu.mobile, hu.card_number FROM saas_community_house_user hu WHERE hu.type = 2 AND hu.status = 1 "
                        + "UNION ALL "
                        + "SELECT hu.mobile, hu.card_number FROM saas_community_house_user hu LEFT JOIN m_match_user_house uh ON hu.community_house_id = uh.house_id "
                        + "WHERE uh.label = 1 AND hu.status = 1 ) tt";


                List<CommunityHouseUser> matchUsers = jdbcTemplate.query(mobileSql, new BeanPropertyRowMapper<>(CommunityHouseUser.class));
                Map<String, CommunityHouseUser> mobileMap = matchUsers.stream().collect(Collectors.toMap(CommunityHouseUser::getMobile, CommunityHouseUser -> CommunityHouseUser));

                String cardSql = "SELECT distinct tt.card_number FROM ("
                        + "SELECT hu.mobile, hu.card_number FROM saas_community_house_user hu WHERE hu.type = 2 AND hu.status = 1 "
                        + "UNION ALL "
                        + "SELECT hu.mobile, hu.card_number FROM saas_community_house_user hu LEFT JOIN m_match_user_house uh ON hu.community_house_id = uh.house_id "
                        + "WHERE uh.label = 1 AND hu.status = 1 ) tt";
                List<CommunityHouseUser> cardUsers = jdbcTemplate.query(cardSql, new BeanPropertyRowMapper<>(CommunityHouseUser.class));
                Map<String, CommunityHouseUser> cardMap = cardUsers.stream().filter(ff -> StringUtils.isNotBlank(ff.getCardNumber())).collect(Collectors.toMap(CommunityHouseUser::getCardNumber, CommunityHouseUser -> CommunityHouseUser));

                // 查询承租人库是否存在此承租人
                Optional<CommunityHouseUser> matchUserOpt = saveOrEditVO.getCommunityHouseUsers().stream()
                        .filter(i -> i.getType() == 1).findFirst();
                log.info("saveOrEdit matchUserOpt={}", JSON.toJSONString(matchUserOpt));
                CommunityHouseUser cmatchUser = null;

                if (matchUserOpt.isPresent()) {
                    cmatchUser = matchUserOpt.get();
                    // 要实现一个用户能添加多个房屋
                    // if (cmatchUser.getId() == null && cmatchUser.getMatchId() == null) {
                    // 	// 首先拿到该对象中的手机号，查找承租人库
                    // 	MatchUser mUser = matchUserRepository.findByPhoneAndDeleteStatus(cmatchUser.getMobile(), false);
                    // 	if (mUser != null) {
                    // 		return ResultBean.failedResultWithMsg("承租人已存在，只能选择存在的承租人");
                    // 	}
                    // }
                }
                MatchUser mUser = null;
                // 承租人库不存在该承租人
                if (ObjectUtil.isNotEmpty(cmatchUser)) {
                    AppUser appUser = appUserRepository.findByPhoneAndTypeAndStatus(cmatchUser.getMobile(), UserLoginTypeEnum.CONSUMER.getValue(), 1);
                    String matchUserId = appUser != null ? appUser.getId() : newAppUser.getId();
                    mUser = matchUserRepository.findByMatchUserId(matchUserId);
                    if (ObjectUtil.isEmpty(mUser)) {
                        // 新增承租人库
                        MatchUser matchUser = new MatchUser();
                        matchUser.setMatchUserId(appUser != null ? appUser.getId() : newAppUser.getId());
                        matchUser.setName(appUser != null ? appUser.getName() : cmatchUser.getName());
                        matchUser.setPhone(cmatchUser.getMobile());
                        matchUser.setDeleteStatus(false);
                        matchUser.setCraeteUserId(token.getId());
                        matchUser.setCreateTime(new Date());
                        matchUser.setLastUpdateTime(new Date());
                        mUser = matchUserRepository.save(matchUser);
                    }

                }
                // 如果是批量添加的
                String[] houseIds = muhVO.getHouseId().split(",");
                List<MatchUserLockAuthor> uList = new ArrayList<>();
                for (int i = 0; i < houseIds.length; i++) {
                    // 获取房屋id,设置房屋为已出租状态
                    // String voHouseId = muhVO.getHouseId();
                    Optional<House> byId1 = houseRepository.findById(houseIds[i]);

                    // 获取房屋类型：性质:1公租房、2廉租房、3商品房、4经济适用房、5其它
                    Integer houseNature = byId1.get().getHouseNature();
                    // 公租房需要去重
                    if (houseNature == 1 || houseNature == 2) {
                        for (CommunityHouseUser communityHouseUser : saveOrEditVO.getCommunityHouseUsers()) {
                            // 新增
                            if (communityHouseUser.getId() == null) {
                                List<CommunityHouseUser> entity = communityHouseUserRepository.findByMobileAndStatus(communityHouseUser.getMobile(), 1);
                                // if (mobileMap.get(communityHouseUser.getMobile()) != null) {
                                //	return ResultBean
                                //			.failedResultWithMsg("手机：" + communityHouseUser.getMobile() + "，已绑定其它房产，不能重复添加");
                                //}

                                // if(StringUtils.isNoneBlank(communityHouseUser.getCardNumber())){
                                //	//List<CommunityHouseUser> entity2 = communityHouseUserRepository.findByCardNumberAndStatus(communityHouseUser.getCardNumber(), 1);
                                //	if (cardMap.get(communityHouseUser.getCardNumber()) != null) {
                                //		return ResultBean.failedResultWithMsg(
                                //				"身份证：" + communityHouseUser.getCardNumber() + "，已绑定其它房产，不能重复添加");
                                //	}
                                //}
                                // 如果是在出租房住的，还能再进保障房入住
                                if (!entity.isEmpty() && communityHouseUser.getType() != 4) {
                                    for (CommunityHouseUser houseUser : entity) {
                                        String communityHouseId = houseUser.getCommunityHouseId();
                                        List<House> byIdAndStatus = houseRepository.findByIdAndStatus(communityHouseId, 1);
                                        if (!byIdAndStatus.isEmpty()) {
                                            House house = byIdAndStatus.get(0);
                                            Integer houseNature1 = house.getHouseNature();
                                            if (houseNature1 == 1 || houseNature1 == 2) {
                                                if (houseUser.getType() != 4) {
                                                    return ResultBean.failedResultWithMsg("手机：" + communityHouseUser.getMobile() + "，已绑定其它房产，不能重复添加");
                                                }
                                            }
                                        }
                                    }
                                }

                            }

                            // 编辑
                            if (communityHouseUser.getId() != null) {
                                Optional<CommunityHouseUser> houseUserOptional = communityHouseUserRepository
                                        .findById(communityHouseUser.getId());
                                CommunityHouseUser houseUser = houseUserOptional.get();
                                // if (!houseUser.getMobile().equals(communityHouseUser.getMobile())) {
                                //     // List<CommunityHouseUser> entity = communityHouseUserRepository.findByMobileAndStatus(communityHouseUser.getMobile(), 1);
                                //     if (mobileMap.get(communityHouseUser.getMobile()) != null) {
                                //         if (communityHouseUser.getType() != 4) {
                                //             return ResultBean.failedResultWithMsg("手机：" + communityHouseUser.getMobile() + "，已绑定其它房产，不能重复添加");
                                //         }
                                //     }
                                // }

                                // 验证身份证
                                if (StringUtils.isNotBlank(communityHouseUser.getCardNumber()) && !communityHouseUser.getCardNumber().equals(houseUser.getCardNumber())) {
                                    // List<CommunityHouseUser> entity2 = communityHouseUserRepository.findByCardNumberAndStatus(communityHouseUser.getCardNumber(), 1);
                                    if (cardMap.get(communityHouseUser.getCardNumber()) != null) {
                                        if (communityHouseUser.getType() != 4) {
                                            return ResultBean.failedResultWithMsg("身份证：" + communityHouseUser.getCardNumber() + "，已绑定其它房产，不能重复添加");
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // 保存设置房屋为已出租状态
                    byId1.get().setLeaseStatus(1);
                    byId1.get().setMatchType(1);
                    houseRepository.save(byId1.get());

                    // 查询是否存在设置记录
                    // MatchUserLockAuthor byMatchUserStock = matchUserLockAuthorRepository.findByHouseId(houseIds[i]);
                    List<MatchUserLockAuthor> byMatchUserStockList = matchUserLockAuthorRepository.findByHouseId(houseIds[i]);
                    if (byMatchUserStockList.size() < 1) {
                        MatchUserLockAuthor byMatchUserStock = new MatchUserLockAuthor();
                        byMatchUserStock.setCreateTime(new Date());
                        byMatchUserStock.setOperatorUserId(1l);
                        // 同时插入临时密码次数记录
                        // 生效年月
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");
                        byMatchUserStock.setEffectiveJulyDate(dateFormat.format(new Date()));
                        byMatchUserStock.setHouseId(houseIds[i]);
                        // 默认5次
                        byMatchUserStock.setAuthorNumber(5);
                        // 默认1天
                        byMatchUserStock.setPasswordValidity(1);
                        byMatchUserStock.setUseNumber(0);
                        // Long matchId = cmatchUser.getMatchId();
                        if (cmatchUser == null && mUser != null && mUser.getId() != null) {
                            byMatchUserStock.setMatchUserStockId(mUser.getId() + "");
                        } else if (cmatchUser != null) {
                            byMatchUserStock.setMatchUserStockId(cmatchUser.getMatchId() + "");
                        }

                        byMatchUserStock.setLastUpdateTime(new Date());
                        uList.add(byMatchUserStock);
                    }
                }
                matchUserLockAuthorRepository.saveAll(uList);
                // 新增单位承租人标签，承租人类型如果选择的是单位承租人，让其所选的单位机构有对应的房屋权限
                if (muhVO.getLabel() == 2) {
                    ArrayList<String> communityHouseIds = new ArrayList<>();
                    Long id = muhVO.getId();
                    // List<CommunityHouseUser> communityHouseUsers = saveOrEditVO.getCommunityHouseUsers();
                    // for (CommunityHouseUser communityHouseUser : communityHouseUsers) {
                    //	String communityHouseId = communityHouseUser.getCommunityHouseId();
                    //	communityHouseIds.add(communityHouseId);
                    //}
                    for (String houseId : houseIds) {
                        communityHouseIds.add(houseId);
                    }
                    List<House> byIdIn = houseRepository.findByIdIn(communityHouseIds);
                    if (byIdIn != null) {
                        for (House house : byIdIn) {
                            house.setUnitLesseeId(id);
                            houseRepository.save(house);
                        }
                    }
                    //	如果是单位承租人则没有添加承租人信息，得自己添加单位承租人为承租人
                    MatchUserHouseVO matchUserHouseVO = saveOrEditVO.getMatchUserHouseVO();
                    Long id1 = matchUserHouseVO.getId();
                    List<UserDepartmentRef> byDepId = userDepartmentRefRepository.findByDepId(id1);
                    String userId = byDepId.get(0).getUserId();
                    // 获取单位承租人机构用户信息
                    User byId = userRepository.findById(userId);
                    String id2 = byId.getId();
                    String name = byId.getName();
                    List<UserDepartmentRef> byUserId = userDepartmentRefRepository.findByUserId(id2);
                    // 获取机构名称
                    if (!byUserId.isEmpty()) {
                        Long depId = byUserId.get(0).getDepId();
                        Optional<Department> byId1 = departmentRepository.findById(depId);
                        String name1 = byId1.get().getName();
                        name = name1;
                    }
                    // 获取承租人库信息
                    MatchUser byMatchUserId = matchUserRepository.findByMatchUserId(id2);
                    if (byMatchUserId == null) {
                        // 新增承租人库
                        MatchUser matchUser = new MatchUser();
                        matchUser.setMatchUserId(id2);
                        matchUser.setName(name);
                        matchUser.setPhone(byId.getMobile());
                        matchUser.setDeleteStatus(false);
                        matchUser.setCraeteUserId(token.getId());
                        matchUser.setCreateTime(new Date());
                        matchUser.setLastUpdateTime(new Date());
                        matchUserRepository.save(matchUser);
                    }
                    // 如果是批量添加的
                    // String[] houseIds = muhVO.getHouseId().split(",");
                    for (int i = 0; i < houseIds.length; i++) {
                        //	获取承租人智能锁信息
                        List<MatchUserLockAuthor> byMatchUserStockList = matchUserLockAuthorRepository.findByHouseId(houseIds[i]);
                        if (byMatchUserStockList.size() < 1) {
                            byMatchUserId = matchUserRepository.findByMatchUserId(id2);
                            Long id3 = null;
                            if (byMatchUserId != null) {
                                id3 = byMatchUserId.getId();
                            }
                            MatchUserLockAuthor byMatchUserStock = new MatchUserLockAuthor();
                            byMatchUserStock.setCreateTime(new Date());
                            byMatchUserStock.setOperatorUserId(1l);
                            // 同时插入临时密码次数记录
                            // 生效年月
                            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");
                            byMatchUserStock.setEffectiveJulyDate(dateFormat.format(new Date()));
                            byMatchUserStock.setHouseId(houseIds[i]);
                            byMatchUserStock.setMatchUserStockId(id3 + "");
                            // 默认5次
                            byMatchUserStock.setAuthorNumber(5);
                            // 默认1天
                            byMatchUserStock.setPasswordValidity(1);
                            byMatchUserStock.setUseNumber(0);
                            byMatchUserStock.setLastUpdateTime(new Date());
                            matchUserLockAuthorRepository.save(byMatchUserStock);
                        }
                        // 先查一遍数据库中是否有该承租人和房屋的关系，根据房屋id查询，有就更新
                        List<MatchUserHouse> byHouseList = matchUserHouseRepository.findByHouseId(houseIds[i]);
                        MatchUserHouse matchUserHouse = null;
                        if (byHouseList.size() < 1) {
                            matchUserHouse = new MatchUserHouse();
                            byMatchUserId = matchUserRepository.findByMatchUserId(id2);
                            Long id3 = null;
                            if (byMatchUserId != null) {
                                id3 = byMatchUserId.getId();
                            }
                            matchUserHouse.setMatchUserStockId(id3 + "");
                            matchUserHouse.setHouseId(houseIds[i]);
                            // List<CommunityHouseUser> users = communityHouseUserRepository.findByCommunityHouseIdAndStatusAndType(houseId, 1, 1);
                            // matchUserHouse.setMemberUserId(!users.isEmpty() ? users.get(0).getId() : null);
                            matchUserHouse.setLabel(matchUserHouseVO.getLabel());
                            matchUserHouse.setCompanyName(matchUserHouseVO.getCompanyName());
                            matchUserHouse.setSocialCreditNumber(matchUserHouseVO.getSocialCreditNumber());
                            matchUserHouse.setStartDate(matchUserHouseVO.getStartDate());
                            matchUserHouse.setEndDate(matchUserHouseVO.getEndDate());
                            matchUserHouse.setChargeMode(matchUserHouseVO.getChargeMode());
                            matchUserHouse.setCreateTime(new Date());
                            // 承租人和房屋关系表
                            matchUserHouseRepository.save(matchUserHouse);
                        }
                    }
                }



                /*// 查询承租人库是否存在此承租人
                Optional<CommunityHouseUser> matchUserOpt = saveOrEditVO.getCommunityHouseUsers().stream()
                        .filter(i -> i.getType() == 1).findFirst();
                log.info("saveOrEdit matchUserOpt={}", JSON.toJSONString(matchUserOpt));
                CommunityHouseUser cmatchUser = null;

                if (matchUserOpt.isPresent()) {
                    cmatchUser = matchUserOpt.get();
                    //要实现一个用户能添加多个房屋
                    // if (cmatchUser.getId() == null && cmatchUser.getMatchId() == null) {
                    // 	// 首先拿到该对象中的手机号，查找承租人库
                    // 	MatchUser mUser = matchUserRepository.findByPhoneAndDeleteStatus(cmatchUser.getMobile(), false);
                    // 	if (mUser != null) {
                    // 		return ResultBean.failedResultWithMsg("承租人已存在，只能选择存在的承租人");
                    // 	}
                    // }
                }*/

                //-------------------------------特殊关系(儿子、女儿)处理-----------------------------------
                // 编辑时由于特殊关系的手机号码增加了后缀，到时无法编辑保存，优化如下：
                List<CommunityHouseUser> communityHouseUsers = saveOrEditVO.getCommunityHouseUsers();
                List<Long> ids = saveOrEditVO.getCommunityHouseUsers().stream().filter(s -> s.getId() != null).map(t -> t.getId()).collect(Collectors.toList());
                if (ids != null && !ids.isEmpty()) {
                    List<CommunityHouseUser> chuList = communityHouseUserRepository.findByIdIn(ids);
                    for (CommunityHouseUser chu : chuList) {
                        for (CommunityHouseUser vo : saveOrEditVO.getCommunityHouseUsers()) {
                            if (vo.getId() != null && chu.getId().intValue() == vo.getId().intValue()) {
                                // 编辑时返回的数据，去掉后缀，保存时恢复原数据的后缀，而后继续后续逻辑处理(手机号码是不可编辑的，所以可以这样处理)
                                if (chu.getMobile().contains("_")) {
                                    vo.setMobile(chu.getMobile());
                                }

                                // 特殊关系编辑时不能修改关系类型
                                if (chu.getRelationTag() != null && vo.getRelationTag() != null && (chu.getRelationTag() == 3 || chu.getRelationTag() == 5) && vo.getRelationTag() != chu.getRelationTag()) {
                                    return ResultBean.failedResultWithMsg("特殊关系(儿子、女儿)同住人，不能修改关系!");
                                }
                            }
                        }
                    }
                }


             /*   // 特殊关系的同住人，如果手机号码与承租人相同，重置同住人手机号码，增加后缀（确保手机号字段唯一）
                for (CommunityHouseUser chu : saveOrEditVO.getCommunityHouseUsers()) {
                    for (CommunityHouseUser vo : saveOrEditVO.getCommunityHouseUsers()) {
                        Integer mobileStatus = vo.getMobileStatus();
                        if (mobileStatus == null) {
                            vo.setMobileStatus(1);
                        }
                        // CommunityHouseUser communityHouseUser = new CommunityHouseUser();
                        // BeanUtil.copyProperties(vo,communityHouseUser);
                        // 1妻子、2丈夫、3儿子、4儿媳、5女儿、6女婿、7父亲、8母亲、9同事、10哥哥、11嫂子、12姐姐、13姐夫、14弟弟、15弟媳、16妹妹、17妹夫、18其他亲属、19朋友、20非亲属
                        if (chu.getType() != null
                                && chu.getType() == 1
                                && chu.getMobile().equals(vo.getMobile())
                                && vo.getRelationTag() != null
                                && vo.getType() != null
                                && vo.getType() == 2
                                && (vo.getRelationTag() == 3 || vo.getRelationTag() == 5 || vo.getMobileStatus() == 0)) {
                            vo.setMobile(vo.getMobile() + "_" + count);
                            count++;
                        }
                    }

                }

                // 如果是编辑，保持后缀有序生成
                for (CommunityHouseUser vo : saveOrEditVO.getCommunityHouseUsers()) {
                    if (vo.getMobile().contains("_")) {
                        // String suffixCount = vo.getMobile().substring(vo.getMobile().indexOf("_") + 1);
                        // if (Integer.parseInt(suffixCount) > count) {
                        //     count = Integer.parseInt(suffixCount);
                        // }
                        // Integer suffixCount = Integer.valueOf(vo.getMobile().substring(vo.getMobile().indexOf("_") + 1)) + count;
                        String substring = vo.getMobile().substring(0, 11);
                        vo.setMobile(substring + "_" + count);
                        count++;
                    }
                }



                // 新增是否有手机号：1是 0否
                for (CommunityHouseUser communityHouseUser : saveOrEditVO.getCommunityHouseUsers()) {
                    if (communityHouseUser.getMobile().contains("_")) {
                        communityHouseUser.setMobileStatus(CommunityHouseUser.MOBILE_STATUS_NO);
                    } else {
                        communityHouseUser.setMobileStatus(CommunityHouseUser.MOBILE_STATUS_YES);
                    }
                }*/
                //---------------------------------------------------------------------------------------------


                // 验证成员之间手机号码与身份证是否重复
                List<String> mobiles = saveOrEditVO.getCommunityHouseUsers().stream().map(mm -> mm.getMobile()).distinct().collect(Collectors.toList());
                if (mobiles.size() < saveOrEditVO.getCommunityHouseUsers().size()) {
                    return ResultBean.failedResultWithMsg("成员手机号码不能重复");
                }

                List<String> cardNumbers1 = saveOrEditVO.getCommunityHouseUsers().stream().filter(mm -> StringUtils.isNotBlank(mm.getCardNumber())).map(mm -> mm.getCardNumber()).collect(Collectors.toList());
                List<String> cardNumbers2 = saveOrEditVO.getCommunityHouseUsers().stream().filter(mm -> StringUtils.isNotBlank(mm.getCardNumber())).map(mm -> mm.getCardNumber()).distinct().collect(Collectors.toList());
                if (cardNumbers1.size() != cardNumbers2.size()) {
                    return ResultBean.failedResultWithMsg("成员身份证号码不能重复");
                }

                //// 查询需去重的手机号码
                // String mobileSql = "SELECT distinct tt.mobile FROM ("
                //		+ "SELECT hu.mobile, hu.card_number FROM saas_community_house_user hu WHERE hu.type = 2 AND hu.status = 1 "
                //		+ "UNION ALL "
                //		+ "SELECT hu.mobile, hu.card_number FROM saas_community_house_user hu LEFT JOIN m_match_user_house uh ON hu.community_house_id = uh.house_id "
                //		+ "WHERE uh.label = 1 AND hu.status = 1 ) tt";
                //
                //
                // List<CommunityHouseUser> matchUsers = jdbcTemplate.query(mobileSql, new BeanPropertyRowMapper<>(CommunityHouseUser.class));
                // Map<String, CommunityHouseUser> mobileMap = matchUsers.stream().collect(Collectors.toMap(CommunityHouseUser::getMobile, CommunityHouseUser -> CommunityHouseUser));
                //
                // String cardSql = "SELECT distinct tt.card_number FROM ("
                //		+ "SELECT hu.mobile, hu.card_number FROM saas_community_house_user hu WHERE hu.type = 2 AND hu.status = 1 "
                //		+ "UNION ALL "
                //		+ "SELECT hu.mobile, hu.card_number FROM saas_community_house_user hu LEFT JOIN m_match_user_house uh ON hu.community_house_id = uh.house_id "
                //		+ "WHERE uh.label = 1 AND hu.status = 1 ) tt";
                // List<CommunityHouseUser> cardUsers = jdbcTemplate.query(cardSql, new BeanPropertyRowMapper<>(CommunityHouseUser.class));
                // Map<String, CommunityHouseUser> cardMap = cardUsers.stream().filter(ff -> StringUtils.isNotBlank(ff.getCardNumber())).collect(Collectors.toMap(CommunityHouseUser::getCardNumber, CommunityHouseUser -> CommunityHouseUser));

                /*//获取房屋id,设置房屋为已出租状态
                String voHouseId = muhVO.getHouseId();
                Optional<House> byId1 = houseRepository.findById(voHouseId);
                byId1.get().setLeaseStatus(1);
                //获取房屋类型：性质:1公租房、2廉租房、3商品房、4经济适用房、5其它
                Integer houseNature = byId1.get().getHouseNature();
                //公租房需要去重
                if (houseNature == 1 || houseNature == 2) {
                    for (CommunityHouseUser communityHouseUser : saveOrEditVO.getCommunityHouseUsers()) {
                        // 新增
                        if (communityHouseUser.getId() == null) {
                            List<CommunityHouseUser> entity = communityHouseUserRepository.findByMobileAndStatus(communityHouseUser.getMobile(), 1);
                            //if (mobileMap.get(communityHouseUser.getMobile()) != null) {
                            //	return ResultBean
                            //			.failedResultWithMsg("手机：" + communityHouseUser.getMobile() + "，已绑定其它房产，不能重复添加");
                            //}

                            //if(StringUtils.isNoneBlank(communityHouseUser.getCardNumber())){
                            //	//List<CommunityHouseUser> entity2 = communityHouseUserRepository.findByCardNumberAndStatus(communityHouseUser.getCardNumber(), 1);
                            //	if (cardMap.get(communityHouseUser.getCardNumber()) != null) {
                            //		return ResultBean.failedResultWithMsg(
                            //				"身份证：" + communityHouseUser.getCardNumber() + "，已绑定其它房产，不能重复添加");
                            //	}
                            //}
                            //如果是在出租房住的，还能再进保障房入住
                            if (!entity.isEmpty()) {
                                for (CommunityHouseUser houseUser : entity) {
                                    String communityHouseId = houseUser.getCommunityHouseId();
                                    List<House> byIdAndStatus = houseRepository.findByIdAndStatus(communityHouseId, 1);
                                    if (!byIdAndStatus.isEmpty()) {
                                        House house = byIdAndStatus.get(0);
                                        Integer houseNature1 = house.getHouseNature();
                                        if (houseNature1 == 1 || houseNature1 ==2) {
                                                return ResultBean.failedResultWithMsg("手机：" + communityHouseUser.getMobile() + "，已绑定其它房产，不能重复添加");
                                        }
                                    }
                                }
                            }

                        }

                        // 编辑
                        if (communityHouseUser.getId() != null) {
                            Optional<CommunityHouseUser> houseUserOptional = communityHouseUserRepository
                                    .findById(communityHouseUser.getId());
                            CommunityHouseUser houseUser = houseUserOptional.get();
                            if (!houseUser.getMobile().equals(communityHouseUser.getMobile())) {
                                //List<CommunityHouseUser> entity = communityHouseUserRepository.findByMobileAndStatus(communityHouseUser.getMobile(), 1);
                                if (mobileMap.get(communityHouseUser.getMobile()) != null) {
                                    return ResultBean.failedResultWithMsg(
                                            "手机：" + communityHouseUser.getMobile() + "，已绑定其它房产，不能重复添加");
                                }
                            }

                            // 验证身份证
                            if (StringUtils.isNotBlank(communityHouseUser.getCardNumber()) && !communityHouseUser.getCardNumber().equals(houseUser.getCardNumber())) {
                                //List<CommunityHouseUser> entity2 = communityHouseUserRepository.findByCardNumberAndStatus(communityHouseUser.getCardNumber(), 1);
                                if (cardMap.get(communityHouseUser.getCardNumber()) != null) {
                                    return ResultBean.failedResultWithMsg(
                                            "身份证：" + communityHouseUser.getCardNumber() + "，已绑定其它房产，不能重复添加");
                                }
                            }
                        }
                    }
                }
                //保存设置房屋为已出租状态
                houseRepository.save(byId1.get());*/
                // 新增租户信息
                for (CommunityHouseUser communityHouseUser : saveOrEditVO.getCommunityHouseUsers()) {
                    // 新增
                    if (communityHouseUser.getId() == null) {
                        // 新增同住人是否给与查看账单标识
                        Integer accountStatus = communityHouseUser.getAccountStatus();
                        if (accountStatus != null) {
                            if (accountStatus == 1) {
                                communityHouseUser.setAccountStatus(1);
                            } else {
                                communityHouseUser.setAccountStatus(2);
                            }
                        }
                        // 查看新增的用户是否已经实名认证了，如果已经实名，就用用户实名认证的名字存储
                        String mobile = communityHouseUser.getMobile();
                        AppUser byPhoneAndStatus = appUserRepository.findByPhoneAndStatusAndCertificationStatusAndType(mobile, 1, 1, UserLoginTypeEnum.CONSUMER.getValue());
                        if (byPhoneAndStatus != null) {
                            String name = byPhoneAndStatus.getName();
                            communityHouseUser.setName(name);
                        }
                        communityHouseUser.setStatus(1);
                        communityHouseUser.setOperatorId(token.getId());
                        communityHouseUser.setOperatorTime(date);
                    }

                    // 租户与房屋管理员区分
                    if (communityHouseUser.getType() != null && communityHouseUser.getType() != 3) {
                        // 查询租户对应的账户信息
                        AppUser appUser = appUserRepository.findByPhoneAndTypeAndStatus(communityHouseUser.getMobile(), UserLoginTypeEnum.CONSUMER.getValue(), 1);
                        if (communityHouseUser.getType() == 1) {
                            if (ObjectUtil.isNotEmpty(appUser) || ObjectUtil.isNotEmpty(newAppUser)) {
                                communityHouseUser.setUserId(ObjectUtil.isNotEmpty(appUser) ? appUser.getId() : newAppUser.getId());
                            }
                        } else {
                            if (appUser != null) {
                                communityHouseUser.setUserId(appUser.getId());
                            } else {
                                User user = userRepository.findByMobile(communityHouseUser.getMobile());
                                if (user != null) {
                                    communityHouseUser.setUserId(user.getId());
                                }
                            }
                        }
                        communityHouseUser.setUserType(1);

                    } else {
                        // 企业管理员的账户信息
                        User user = userRepository.findByMobile(communityHouseUser.getMobile());
                        if (user != null) {
                            communityHouseUser.setUserId(user.getId());
                        }
                        communityHouseUser.setUserType(2);
                    }
                    communityHouseUser.setChangeLabel(1);
                }
                // String[] houseIds = muhVO.getHouseId().split(",");
                // String[] houseIds = muhVO.getHouseId().split(",");
                /*MatchUser mUser = null;
                // 承租人库不存在该承租人
                if (cmatchUser != null && cmatchUser.getId() == null && cmatchUser.getMatchId() == null) {
                    // 查询租户对应的APP账户信息
                    AppUser appUser = appUserRepository.findByPhone(cmatchUser.getMobile());
                    // 新增承租人库
                    MatchUser matchUser = new MatchUser();
                    matchUser.setMatchUserId(appUser != null ? appUser.getId() : null);
                    matchUser.setName(cmatchUser.getName());
                    matchUser.setPhone(cmatchUser.getMobile());
                    matchUser.setDeleteStatus(false);
                    matchUser.setCraeteUserId(token.getId());
                    matchUser.setCreateTime(new Date());
                    matchUser.setLastUpdateTime(new Date());
                    mUser = matchUserRepository.save(matchUser);


                }*/

                /*List<MatchUserLockAuthor> uList = new ArrayList<>();
                for (int i = 0; i < houseIds.length; i++) {
                    //获取房屋id,设置房屋为已出租状态
                    //String voHouseId = muhVO.getHouseId();
                    Optional<House> byId1 = houseRepository.findById(houseIds[i]);

                    //获取房屋类型：性质:1公租房、2廉租房、3商品房、4经济适用房、5其它
                    Integer houseNature = byId1.get().getHouseNature();
                    //公租房需要去重
                    if (houseNature == 1 || houseNature == 2) {
                        for (CommunityHouseUser communityHouseUser : saveOrEditVO.getCommunityHouseUsers()) {
                            // 新增
                            if (communityHouseUser.getId() == null) {
                                List<CommunityHouseUser> entity = communityHouseUserRepository.findByMobileAndStatus(communityHouseUser.getMobile(), 1);
                                //if (mobileMap.get(communityHouseUser.getMobile()) != null) {
                                //	return ResultBean
                                //			.failedResultWithMsg("手机：" + communityHouseUser.getMobile() + "，已绑定其它房产，不能重复添加");
                                //}

                                //if(StringUtils.isNoneBlank(communityHouseUser.getCardNumber())){
                                //	//List<CommunityHouseUser> entity2 = communityHouseUserRepository.findByCardNumberAndStatus(communityHouseUser.getCardNumber(), 1);
                                //	if (cardMap.get(communityHouseUser.getCardNumber()) != null) {
                                //		return ResultBean.failedResultWithMsg(
                                //				"身份证：" + communityHouseUser.getCardNumber() + "，已绑定其它房产，不能重复添加");
                                //	}
                                //}
                                //如果是在出租房住的，还能再进保障房入住
                                if (!entity.isEmpty()) {
                                    for (CommunityHouseUser houseUser : entity) {
                                        String communityHouseId = houseUser.getCommunityHouseId();
                                        List<House> byIdAndStatus = houseRepository.findByIdAndStatus(communityHouseId, 1);
                                        if (!byIdAndStatus.isEmpty()) {
                                            House house = byIdAndStatus.get(0);
                                            Integer houseNature1 = house.getHouseNature();
                                            if (houseNature1 == 1 || houseNature1 ==2) {
                                                return ResultBean.failedResultWithMsg("手机：" + communityHouseUser.getMobile() + "，已绑定其它房产，不能重复添加");
                                            }
                                        }
                                    }
                                }

                            }

                            // 编辑
                            if (communityHouseUser.getId() != null) {
                                Optional<CommunityHouseUser> houseUserOptional = communityHouseUserRepository
                                        .findById(communityHouseUser.getId());
                                CommunityHouseUser houseUser = houseUserOptional.get();
                                if (!houseUser.getMobile().equals(communityHouseUser.getMobile())) {
                                    //List<CommunityHouseUser> entity = communityHouseUserRepository.findByMobileAndStatus(communityHouseUser.getMobile(), 1);
                                    if (mobileMap.get(communityHouseUser.getMobile()) != null) {
                                        return ResultBean.failedResultWithMsg(
                                                "手机：" + communityHouseUser.getMobile() + "，已绑定其它房产，不能重复添加");
                                    }
                                }

                                // 验证身份证
                                if (StringUtils.isNotBlank(communityHouseUser.getCardNumber()) && !communityHouseUser.getCardNumber().equals(houseUser.getCardNumber())) {
                                    //List<CommunityHouseUser> entity2 = communityHouseUserRepository.findByCardNumberAndStatus(communityHouseUser.getCardNumber(), 1);
                                    if (cardMap.get(communityHouseUser.getCardNumber()) != null) {
                                        return ResultBean.failedResultWithMsg(
                                                "身份证：" + communityHouseUser.getCardNumber() + "，已绑定其它房产，不能重复添加");
                                    }
                                }
                            }
                        }
                    }
                    //保存设置房屋为已出租状态
                    byId1.get().setLeaseStatus(1);
                    byId1.get().setMatchType(1);
                    houseRepository.save(byId1.get());
                    // 查询是否存在设置记录
                    //MatchUserLockAuthor byMatchUserStock = matchUserLockAuthorRepository.findByHouseId(houseIds[i]);
                    List<MatchUserLockAuthor> byMatchUserStockList = matchUserLockAuthorRepository.findByHouseId(houseIds[i]);
                    if(byMatchUserStockList.size() < 1 ){
                        MatchUserLockAuthor byMatchUserStock = new MatchUserLockAuthor();
                        byMatchUserStock.setCreateTime(new Date());
                        byMatchUserStock.setOperatorUserId(1l);
                        // 同时插入临时密码次数记录
                        // 生效年月
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");
                        byMatchUserStock.setEffectiveJulyDate(dateFormat.format(new Date()));
                        byMatchUserStock.setHouseId(houseIds[i]);
                        // 默认5次
                        byMatchUserStock.setAuthorNumber(5);
                        // 默认1天
                        byMatchUserStock.setPasswordValidity(1);
                        byMatchUserStock.setUseNumber(0);
                        // Long matchId = cmatchUser.getMatchId();
                        if (cmatchUser == null && mUser != null && mUser.getId() != null) {
                            byMatchUserStock.setMatchUserStockId(mUser.getId() + "");
                        } else if(cmatchUser != null){
                            byMatchUserStock.setMatchUserStockId(cmatchUser.getMatchId() + "");
                        }

                        byMatchUserStock.setLastUpdateTime(new Date());
                        uList.add(byMatchUserStock);
                    }
                }
                matchUserLockAuthorRepository.saveAll(uList);*/

                List<BacklogItemVo> backlogItemList = new ArrayList<>();

                for (String houseId : houseIds) {
                    // 先查一遍数据库中是否有该承租人和房屋的关系，根据房屋id查询，有就更新
                    List<MatchUserHouse> byHouseList = matchUserHouseRepository.findByHouseId(houseId);
                    MatchUserHouse matchUserHouse = null;
                    MatchUserHouseVO matchUserHouseVO = saveOrEditVO.getMatchUserHouseVO();
                    if (byHouseList == null || byHouseList.isEmpty()) {
                        matchUserHouse = new MatchUserHouse();
                    } else {
                        // 更新
                        matchUserHouse = byHouseList.get(0);
                    }

                    if (cmatchUser == null && mUser == null) {
                        break;
                    }

                    if (cmatchUser.getMatchId() == null && mUser != null && mUser.getId() != null) {
                        matchUserHouse.setMatchUserStockId(mUser.getId() + "");
                    } else if (cmatchUser.getMatchId() != null) {
                        matchUserHouse.setMatchUserStockId(cmatchUser.getMatchId() + "");
                    }

                    matchUserHouse.setHouseId(houseId);
                    // List<CommunityHouseUser> users = communityHouseUserRepository.findByCommunityHouseIdAndStatusAndType(houseId, 1, 1);
                    // matchUserHouse.setMemberUserId(!users.isEmpty() ? users.get(0).getId() : null);
                    matchUserHouse.setLabel(matchUserHouseVO.getLabel());
                    matchUserHouse.setCompanyName(matchUserHouseVO.getCompanyName());
                    matchUserHouse.setSocialCreditNumber(matchUserHouseVO.getSocialCreditNumber());
                    matchUserHouse.setStartDate(matchUserHouseVO.getStartDate());
                    matchUserHouse.setEndDate(matchUserHouseVO.getEndDate());
                    matchUserHouse.setChargeMode(matchUserHouseVO.getChargeMode());
                    matchUserHouse.setCreateTime(new Date());
                    // 承租人和房屋关系表
                    matchUserHouseRepository.save(matchUserHouse);
                }

                for (String houseId : houseIds) {
                    Map<String, Long> orgId = new HashMap<>();

                    String residenceCommunityId = null;
                    Optional<House> byId = houseRepository.findById(houseId);

                    if (byId.isPresent()) {
                        House house = byId.get();
                        residenceCommunityId = house.getResidenceCommunityId();
                        orgId.put("orgId", house.getOrgId());
                        orgId.put("housePropertyId", house.getHousePropertyId());
                    }
                    // 整租房产添加成员如果有绑定智能锁的情况下添加智能锁信息
                    List<SmartLock> lockList = smartLockRepository.findByHouseIdAndStatus(houseId, 1);
                    // 合租房产添加成员如果有绑定智能锁的情况下添加智能锁信息
                    List<House> byIdAndStatus = houseRepository.findByIdAndStatus(houseId, 1);
                    String housemateId = null;
                    if (byIdAndStatus.size() > 0) {
                        housemateId = byIdAndStatus.get(0).getHousemateId();
                    }
                    // 获取合租房产的智能锁信息
                    List<SmartLock> lockSubHouseList = smartLockRepository.findByHouseIdAndStatus(housemateId, 1);
                    if (!lockList.isEmpty() || !lockSubHouseList.isEmpty()) {// 已安装锁
                        SmartLock smartLock = lockList.size() > 0 ? lockList.get(0) : lockSubHouseList.get(0);
                        Long lockId = lockList.size() > 0 ? lockList.get(0).getId() : lockSubHouseList.get(0).getId();
                        // 租户id
                        List<CommunityHouseUser> tenantList = saveOrEditVO.getCommunityHouseUsers().stream()
                                .filter(c -> c.getType() == 1).collect(Collectors.toList());
                        String matchUserId = null;
                        String matchUserName = null;
                        if (!tenantList.isEmpty()) {
                            matchUserId = tenantList.get(0).getUserId();
                            matchUserName = tenantList.get(0).getName();

                            String mobile = tenantList.get(0).getMobile();
                            // 查看新增的用户是否已经实名认证了，如果已经实名，就用用户实名认证的名字存储
                            AppUser byPhoneAndStatus = appUserRepository.findByPhoneAndStatusAndCertificationStatusAndType(mobile, 1, 1, UserLoginTypeEnum.CONSUMER.getValue());
                            if (ObjectUtil.isNotEmpty(byPhoneAndStatus)) {
                                matchUserName = byPhoneAndStatus.getName();
                            }
                        }

                        // 更新锁承租人id、姓名
                        smartLock.setMatchUserId(matchUserId);
                        smartLock.setMatchUserName(matchUserName);
                        smartLockRepository.save(smartLock);
                        for (CommunityHouseUser communityHouseUser : saveOrEditVO.getCommunityHouseUsers()) {
                            Long id = communityHouseUser.getId();
                            String name = communityHouseUser.getName();
                            String mobile = communityHouseUser.getMobile();

                            communityHouseUser.setCommunityHouseId(houseId);
                            communityHouseUser.setCommunityId(residenceCommunityId);
                            if (id == null) {// 新增
                                CommunityHouseUser entity = new CommunityHouseUser();
                                BeanUtils.copyProperties(communityHouseUser, entity);
                                // 新增添加成员的时候，如果用户已经实名了，需要存用户的身份证号和人脸照 xiaolong20230330
                                AppUser byPhoneAndStatusAndCertificationStatus = appUserRepository.findByPhoneAndStatusAndCertificationStatusAndType(mobile, 1, 1, UserLoginTypeEnum.CONSUMER.getValue());
                                if (byPhoneAndStatusAndCertificationStatus != null) {
                                    String facePic = byPhoneAndStatusAndCertificationStatus.getFacePic();
                                    String cardNumber = byPhoneAndStatusAndCertificationStatus.getCardNumber();
                                    entity.setHumanFaceImage(facePic);
                                    entity.setCardNumber(cardNumber);
                                }
                                CommunityHouseUser save = communityHouseUserRepository.save(entity);
                                // 产生待办事项, type: 1新增同住人  2 新增承租人 3 删除同住人  4 删除承租人
                                Integer type = save.getType() == 1 ? 2 : 1;
                                BacklogItemVo backlogItemVo = new BacklogItemVo();
                                backlogItemVo.setCommunityHouseId(houseId);// 房产id
                                backlogItemVo.setUserOrgId(token.getEnterpriseId());// 个人组织id
                                backlogItemVo.setName(communityHouseUser.getName());// 人员名称
                                backlogItemVo.setOperatorId(token.getId());// 操作人id
                                backlogItemVo.setId(save.getId());// 房产成员信息登记表明细表id   saas_community_house_user
                                backlogItemVo.setType(type);// 1新增同住人  2 新增承租人 3 删除同住人  4 删除承租人
                                backlogItemVo.setPhone(save.getMobile());// 手机号
                                backlogItemList.add(backlogItemVo);

                                // backlogItem(houseId, token.getEnterpriseId(), communityHouseUser.getName(), token.getId(), save.getId(), type);

                                SmartLockAuth auth = new SmartLockAuth();
                                auth.setLockId(lockId);
                                auth.setHouseId(smartLock.getHouseId());
                                auth.setBindType(0);// 单位
                                auth.setMatchUserId(matchUserId);
                                auth.setAuthorUserId(communityHouseUser.getUserId());
                                if (communityHouseUser.getType() == 1) {
                                    auth.setUserType(1);
                                } else if (communityHouseUser.getType() == 2) {
                                    auth.setUserType(2);
                                } else if (communityHouseUser.getType() == 3) {
                                    auth.setUserType(3);
                                } else {
                                    auth.setUserType(4);
                                }
                                auth.setUserName(name);
                                auth.setMobile(mobile);

                                if (smartLock.getMechineStatus() == 2) {
                                    auth.setPwdStatus(2);
                                    auth.setFingerprintStatus(2);
                                    auth.setCardStatus(2);
                                    auth.setCpuStatus(2);
                                    auth.setBleStatus(2);
                                    auth.setFaceStatus(2);
                                } else {
                                    auth.setPwdStatus(0);
                                    auth.setFingerprintStatus(0);
                                    auth.setCardStatus(0);
                                    auth.setCpuStatus(0);
                                    auth.setBleStatus(0);
                                    auth.setFaceStatus(0);
                                }
                                auth.setRelationTag(communityHouseUser.getRelationTag());
                                auth.setCreateTime(date);
                                auth.setCommunityUserId(save.getId());
                                // 新增合租房屋子房屋Id
                                auth.setSubHouseId(communityHouseUser.getCommunityHouseId());
                                // 新增房屋号
                                List<House> byIdAndStatus1 = houseRepository.findByIdAndStatus(communityHouseUser.getCommunityHouseId(), 1);
                                String num = null;
                                if (byIdAndStatus1.size() > 0) {
                                    num = byIdAndStatus1.get(0).getRoomNumber();
                                }
                                auth.setRoomNumber(num);
                                smartLockAuthRepository.save(auth);

                                Long orgId1 = orgId.get("orgId");
                                Long housePropertyId1 = orgId.get("housePropertyId");
                                ArrayList<Long> orgIds = new ArrayList<>();
                                orgIds.add(orgId1);
                                orgIds.add(housePropertyId1);
                                // 产生承租人余额账户
                                /*if (communityHouseUser.getType() == 1) {
                                    List<HouseRemainingRelation> remRelationList = houseRemainingRelationRepository.findByOrgIdInAndHouseId(orgIds, houseId);
                                    if (!remRelationList.isEmpty()){
                                        List<Long> remId = remRelationList.stream().map(HouseRemainingRelation::getRemainingId).collect(Collectors.toList());
                                        List<HouseRemaining> houseRemainings = houseRemainingRepository.findByIdIn(remId);
                                        if (!houseRemainings.isEmpty()){
                                            houseRemainings.forEach(m-> m.setStatus(RemainingStatusEnum.RENUNCIATION.getValue()));
                                        }
                                        houseRemainingRelationRepository.deleteAll(remRelationList);
                                    }


                                    if (orgId1 != null ){
                                        HouseRemaining rem = new HouseRemaining();
                                        rem.setRemainingType(1);
                                        rem.setType(muhVO.getLabel());
                                        rem.setHouseId(houseId);
                                        rem.setOrgId(orgId1);
                                        rem.setBalanceFee(0);
                                        rem.setCashPledge(0);
                                        rem.setMatchUserId(save.getUserId());
                                        rem.setLastUpdateTime(date);
                                        rem.setCreateTime(date);
                                        rem.setStatus(RemainingStatusEnum.NORMAL.getValue());
                                        HouseRemaining remSave = houseRemainingRepository.save(rem);


                                        HouseRemainingRelation remRelation = new HouseRemainingRelation();
                                        remRelation.setHouseId(houseId);
                                        remRelation.setRemainingId(remSave.getId());
                                        remRelation.setCreateTime(date);
                                        remRelation.setOrgId(orgId1);
                                        houseRemainingRelationRepository.save(remRelation);
                                    }
                                    if (housePropertyId1 != null ){
                                        HouseRemaining rem = new HouseRemaining();
                                        rem.setRemainingType(2);
                                        rem.setType(muhVO.getLabel());
                                        rem.setHouseId(houseId);
                                        rem.setOrgId(housePropertyId1);
                                        rem.setBalanceFee(0);
                                        rem.setCashPledge(0);
                                        rem.setMatchUserId(save.getUserId());
                                        rem.setLastUpdateTime(date);
                                        rem.setCreateTime(date);
                                        rem.setStatus(RemainingStatusEnum.NORMAL.getValue());
                                        HouseRemaining remSave = houseRemainingRepository.save(rem);


                                        HouseRemainingRelation remRelation = new HouseRemainingRelation();
                                        remRelation.setHouseId(houseId);
                                        remRelation.setRemainingId(remSave.getId());
                                        remRelation.setCreateTime(date);
                                        remRelation.setOrgId(housePropertyId1);
                                        houseRemainingRelationRepository.save(remRelation);
                                    }
                                }*/

                                House house = houseRepository.findById(houseId).get();
                                if (saveOrEditVO.getUserCount() == 0 && !house.getHouseNature().equals(7)) {
                                    //	获取合租房产下的房产承租人信息
                                    List<MatchUserHouse> byHouseId = matchUserHouseRepository.findByHouseId(communityHouseUser.getCommunityHouseId());
                                    if (!byHouseId.isEmpty()) {
                                        String matchUserStockId = byHouseId.get(0).getMatchUserStockId();
                                        //	根据承租人和房产的承租人id查询承认人表的房产承租人id
                                        Optional<MatchUser> matchUserRepositoryById = matchUserRepository.findById(Long.parseLong(matchUserStockId));
                                        if (matchUserRepositoryById.isPresent()) {
                                            // 产权下的用户承租人id
                                            MatchUser byMatchUserId = matchUserRepositoryById.get();
                                            // 产权下的用户承租人id
                                            String matchUserId1 = byMatchUserId.getMatchUserId();
                                            List<HouseRemainingRelation> remRelationList = houseRemainingRelationRepository.findByOrgIdInAndHouseId(orgIds, houseId);

                                            if (remRelationList.isEmpty()) {
                                                if (orgId1 != null) {
                                                    HouseRemaining rem = new HouseRemaining();
                                                    rem.setRemainingType(1);
                                                    rem.setType(muhVO.getLabel());
                                                    rem.setHouseId(houseId);
                                                    rem.setOrgId(orgId1);
                                                    rem.setBalanceFee(0);
                                                    rem.setCashPledge(0);
                                                    rem.setMatchUserId(matchUserId1);
                                                    rem.setLastUpdateTime(date);
                                                    rem.setCreateTime(date);
                                                    rem.setStatus(RemainingStatusEnum.NORMAL.getValue());
                                                    HouseRemaining remSave = houseRemainingRepository.save(rem);


                                                    HouseRemainingRelation remRelation = new HouseRemainingRelation();
                                                    remRelation.setHouseId(houseId);
                                                    remRelation.setRemainingId(remSave.getId());
                                                    remRelation.setCreateTime(date);
                                                    remRelation.setOrgId(orgId1);
                                                    houseRemainingRelationRepository.save(remRelation);
                                                }
                                                if (housePropertyId1 != null && !orgId1.equals(housePropertyId1)) {

                                                    HouseRemaining rem = new HouseRemaining();
                                                    rem.setRemainingType(2);
                                                    rem.setType(muhVO.getLabel());
                                                    rem.setHouseId(houseId);
                                                    rem.setOrgId(housePropertyId1);
                                                    rem.setBalanceFee(0);
                                                    rem.setCashPledge(0);
                                                    rem.setMatchUserId(matchUserId1);
                                                    rem.setLastUpdateTime(date);
                                                    rem.setCreateTime(date);
                                                    rem.setStatus(RemainingStatusEnum.NORMAL.getValue());
                                                    HouseRemaining remSave = houseRemainingRepository.save(rem);


                                                    HouseRemainingRelation remRelation = new HouseRemainingRelation();
                                                    remRelation.setHouseId(houseId);
                                                    remRelation.setRemainingId(remSave.getId());
                                                    remRelation.setCreateTime(date);
                                                    remRelation.setOrgId(housePropertyId1);
                                                    houseRemainingRelationRepository.save(remRelation);
                                                }
                                            }
                                            if (muhVO.getLabel() == 2) {
                                                List<DepartmentRemainingRef> depRemainingRef = departmentRemainingRefRepository.findByDepIdAndHouseId(muhVO.getId(), houseId);
                                                // 账户不存在
                                                if (depRemainingRef.isEmpty()) {
                                                    if (orgId1 != null) {
                                                        DepartmentRemaining depRem = departmentRemainingRepository.findByDepIdAndOrgId(muhVO.getId(), orgId1);
                                                        if (depRem == null) {
                                                            DepartmentRemaining departmentRemaining = new DepartmentRemaining();
                                                            departmentRemaining.setDepId(muhVO.getId());
                                                            departmentRemaining.setDepName(muhVO.getCompanyName());
                                                            departmentRemaining.setHouseId(houseId);
                                                            departmentRemaining.setOrgId(orgId1);
                                                            departmentRemaining.setBalanceFee(0);
                                                            departmentRemaining.setCashPledge(0);
                                                            departmentRemaining.setLastUpdateTime(date);
                                                            departmentRemaining.setCreateTime(date);
                                                            departmentRemaining.setStatus(1);
                                                            depRem = departmentRemainingRepository.save(departmentRemaining);
                                                        }

                                                        DepartmentRemainingRef remainingRef = new DepartmentRemainingRef();
                                                        remainingRef.setDepId(muhVO.getId());
                                                        remainingRef.setDepName(muhVO.getCompanyName());
                                                        remainingRef.setOrgId(orgId1);
                                                        remainingRef.setHouseId(houseId);
                                                        remainingRef.setRemainingId(depRem.getId());
                                                        remainingRef.setCreateTime(date);
                                                        remainingRef.setRentWithholdStatus(1);
                                                        remainingRef.setElseWithholdStatus(1);
                                                        departmentRemainingRefRepository.save(remainingRef);
                                                    }
                                                    if (housePropertyId1 != null && !orgId1.equals(housePropertyId1)) {
                                                        DepartmentRemaining depRem = departmentRemainingRepository.findByDepIdAndOrgId(muhVO.getId(), housePropertyId1);
                                                        if (depRem == null) {
                                                            DepartmentRemaining departmentRemaining = new DepartmentRemaining();
                                                            departmentRemaining.setDepId(muhVO.getId());
                                                            departmentRemaining.setDepName(muhVO.getCompanyName());
                                                            departmentRemaining.setHouseId(houseId);
                                                            departmentRemaining.setOrgId(housePropertyId1);
                                                            departmentRemaining.setBalanceFee(0);
                                                            departmentRemaining.setCashPledge(0);
                                                            departmentRemaining.setLastUpdateTime(date);
                                                            departmentRemaining.setCreateTime(date);
                                                            departmentRemaining.setStatus(1);
                                                            depRem = departmentRemainingRepository.save(departmentRemaining);
                                                        }
                                                        DepartmentRemainingRef remainingRef = new DepartmentRemainingRef();
                                                        remainingRef.setDepId(muhVO.getId());
                                                        remainingRef.setDepName(muhVO.getCompanyName());
                                                        remainingRef.setOrgId(housePropertyId1);
                                                        remainingRef.setHouseId(houseId);
                                                        remainingRef.setRemainingId(depRem.getId());
                                                        remainingRef.setCreateTime(date);
                                                        remainingRef.setRentWithholdStatus(1);
                                                        remainingRef.setElseWithholdStatus(1);
                                                        departmentRemainingRefRepository.save(remainingRef);
                                                    }
                                                }
                                            }

                                        }
                                    }
                                }


                                //	新增流动人员数据
                                //	类型：1租户 2成员 3房屋管理员 4房管员 (3房屋管理员和4房管员不用记录)
                                if (communityHouseUser.getType() == 1 || communityHouseUser.getType() == 2) {
                                    UserFloatingPopulationRecord record = new UserFloatingPopulationRecord();
                                    record.setUserId(communityHouseUser.getUserId());
                                    record.setUserPhone(communityHouseUser.getMobile());
                                    record.setUserName(communityHouseUser.getName());
                                    record.setHouseId(communityHouseUser.getCommunityHouseId());
                                    record.setOrgId(house.getOrgId());
                                    record.setType(UserFloatingPopulationRecord.RECORD_TYPE_CHECK_IN);
                                    record.setCreateBy(token.getId());
                                    record.setCreateTime(new Date());
                                    userFloatingPopulationRecordService.insertUserFloatingPopulationRecord(record);
                                }
                            }

                            if (id != null) {// 编辑
                                // 首先查询数据库，如果数据库中的数据不为null或者""，再进入方法
                                // 判断如果humanFaceImage 为 null或者为""，就调用oss中删除文件的操作
                                if (StringUtils.isBlank(communityHouseUser.getHumanFaceImage())) {
                                    // 根据userId先查到数据
                                    List<CommunityHouseUser> byUserIdAndStatus = communityHouseUserRepository
                                            .findByIdAndStatus(communityHouseUser.getId(), 1);
                                    byUserIdAndStatus.forEach(item -> {
                                        if (StringUtils.isNotBlank(item.getHumanFaceImage())) {
                                            ossService.deleteObject(null, item.getHumanFaceImage());
                                        }
                                    });
                                }
                                String humanFaceImage = communityHouseUser.getHumanFaceImage();
                                if (humanFaceImage != null) {
                                    humanFaceImage = humanFaceImage.replace(ossBucketUrl, "");
                                }
                                communityHouseUser.setHumanFaceImage(humanFaceImage);
                                communityHouseUserRepository.save(communityHouseUser);

                                SmartLockAuth auth = smartLockAuthRepository.findByCommunityUserId(id);
                                auth.setMatchUserId(matchUserId);
                                auth.setAuthorUserId(communityHouseUser.getUserId());
                                auth.setUserName(name);
                                auth.setMobile(mobile);
                                auth.setRelationTag(communityHouseUser.getRelationTag());
                                if (communityHouseUser.getType() == 1) {
                                    auth.setUserType(1);
                                } else if (communityHouseUser.getType() == 2) {
                                    auth.setUserType(2);
                                } else if (communityHouseUser.getType() == 3) {
                                    auth.setUserType(3);// 房屋管理员
                                } else {
                                    auth.setUserType(4);// 房管员
                                }
                                smartLockAuthRepository.save(auth);
                            }
                        }
                    } else {// 未安装锁
                        for (CommunityHouseUser communityHouseUser : saveOrEditVO.getCommunityHouseUsers()) {
                            CommunityHouseUser entity = new CommunityHouseUser();
                            communityHouseUser.setCommunityHouseId(houseId);
                            communityHouseUser.setCommunityId(residenceCommunityId);
                            // 区分编辑与新增
                            Long id = communityHouseUser.getId();
                            String humanFaceImage = communityHouseUser.getHumanFaceImage();
                            if (humanFaceImage != null) {
                                humanFaceImage = humanFaceImage.replace(ossBucketUrl, "");
                            }
                            communityHouseUser.setHumanFaceImage(humanFaceImage);
                            BeanUtils.copyProperties(communityHouseUser, entity);
                            // 新增添加成员的时候，如果用户已经实名了，需要存在用户的身份证号和人脸照 xiaolong20230330
                            String mobile = communityHouseUser.getMobile();
                            AppUser byPhoneAndStatusAndCertificationStatus = appUserRepository.findByPhoneAndStatusAndCertificationStatusAndType(mobile, 1, 1, UserLoginTypeEnum.CONSUMER.getValue());
                            if (byPhoneAndStatusAndCertificationStatus != null) {
                                String facePic = byPhoneAndStatusAndCertificationStatus.getFacePic();
                                String cardNumber = byPhoneAndStatusAndCertificationStatus.getCardNumber();
                                entity.setHumanFaceImage(facePic);
                                entity.setCardNumber(cardNumber);
                            }
                            communityHouseUserRepository.save(entity);


                            if (id == null) {
                                Integer type = entity.getType() == 1 ? 2 : 1;
                                BacklogItemVo backlogItemVo = new BacklogItemVo();
                                backlogItemVo.setCommunityHouseId(houseId);// 房产id
                                backlogItemVo.setUserOrgId(token.getEnterpriseId());// 个人组织id
                                backlogItemVo.setName(communityHouseUser.getName());// 人员名称
                                backlogItemVo.setOperatorId(token.getId());// 操作人id
                                backlogItemVo.setId(entity.getId());// 房产成员信息登记表明细表id   saas_community_house_user
                                backlogItemVo.setType(type);// 1新增同住人  2 新增承租人 3 删除同住人  4 删除承租人
                                backlogItemVo.setPhone(entity.getMobile());// 手机号
                                backlogItemList.add(backlogItemVo);

                                // 产生待办事项
//	                    backlogItem(houseId, token.getEnterpriseId(), communityHouseUser.getName(), token.getId(),
//	                    		entity.getId(), type);
                                Long orgId1 = orgId.get("orgId");
                                Long housePropertyId1 = orgId.get("housePropertyId");
                                ArrayList<Long> orgIds = new ArrayList<>();
                                orgIds.add(orgId1);
                                orgIds.add(housePropertyId1);
                                // 产生承租人余额账户
                                /*if (communityHouseUser.getType() == 1) {
                                    List<HouseRemainingRelation> remRelationList = houseRemainingRelationRepository.findByOrgIdInAndHouseId(orgIds, houseId);
                                    if (!remRelationList.isEmpty()){
                                        List<Long> remId = remRelationList.stream().map(HouseRemainingRelation::getRemainingId).collect(Collectors.toList());
                                        List<HouseRemaining> houseRemainings = houseRemainingRepository.findByIdIn(remId);
                                        if (!houseRemainings.isEmpty()){
                                            houseRemainings.forEach(m-> m.setStatus(RemainingStatusEnum.DEL.getValue()));
                                        }
                                        houseRemainingRelationRepository.deleteAll(remRelationList);
                                    }


                                    if (orgId1 != null ){
                                        HouseRemaining rem = new HouseRemaining();
                                        rem.setRemainingType(1);
                                        rem.setType(muhVO.getLabel());
                                        rem.setHouseId(houseId);
                                        rem.setOrgId(orgId1);
                                        rem.setBalanceFee(0);
                                        rem.setCashPledge(0);
                                        rem.setMatchUserId(communityHouseUser.getUserId());
                                        rem.setLastUpdateTime(date);
                                        rem.setCreateTime(date);
                                        rem.setStatus(RemainingStatusEnum.NORMAL.getValue());
                                        HouseRemaining remSave = houseRemainingRepository.save(rem);


                                        HouseRemainingRelation remRelation = new HouseRemainingRelation();
                                        remRelation.setHouseId(houseId);
                                        remRelation.setRemainingId(remSave.getId());
                                        remRelation.setCreateTime(date);
                                        remRelation.setOrgId(orgId1);
                                        houseRemainingRelationRepository.save(remRelation);
                                    }
                                    if (housePropertyId1 != null ){
                                        HouseRemaining rem = new HouseRemaining();
                                        rem.setRemainingType(2);
                                        rem.setType(muhVO.getLabel());
                                        rem.setHouseId(houseId);
                                        rem.setOrgId(housePropertyId1);
                                        rem.setBalanceFee(0);
                                        rem.setCashPledge(0);
                                        rem.setMatchUserId(communityHouseUser.getUserId());
                                        rem.setLastUpdateTime(date);
                                        rem.setCreateTime(date);
                                        rem.setStatus(RemainingStatusEnum.NORMAL.getValue());
                                        HouseRemaining remSave = houseRemainingRepository.save(rem);


                                        HouseRemainingRelation remRelation = new HouseRemainingRelation();
                                        remRelation.setHouseId(houseId);
                                        remRelation.setRemainingId(remSave.getId());
                                        remRelation.setCreateTime(date);
                                        remRelation.setOrgId(housePropertyId1);
                                        houseRemainingRelationRepository.save(remRelation);
                                    }
                                }*/
                                House house = houseRepository.findById(houseId).get();
                                if (saveOrEditVO.getUserCount() == 0 && !house.getHouseNature().equals(7)) {
                                    //	获取合租房产下的房产承租人信息
                                    List<MatchUserHouse> byHouseId = matchUserHouseRepository.findByHouseId(communityHouseUser.getCommunityHouseId());
                                    if (CollectionUtil.isNotEmpty(byHouseId)) {
                                        String matchUserStockId = byHouseId.get(0).getMatchUserStockId();
                                        //	根据承租人和房产的承租人id查询承认人表的房产承租人id
                                        Optional<MatchUser> matchUserRepositoryById = matchUserRepository.findById(Long.parseLong(matchUserStockId));
                                        if (matchUserRepositoryById.isPresent()) {
                                            // 产权下的用户承租人id
                                            MatchUser byMatchUserId = matchUserRepositoryById.get();
                                            // 产权下的用户承租人id
                                            String matchUserId1 = byMatchUserId.getMatchUserId();
                                            List<HouseRemainingRelation> remRelationList = houseRemainingRelationRepository.findByOrgIdInAndHouseId(orgIds, houseId);

                                            if (remRelationList.isEmpty()) {
                                                if (orgId1 != null) {
                                                    HouseRemaining rem = new HouseRemaining();
                                                    rem.setRemainingType(1);
                                                    rem.setType(muhVO.getLabel());
                                                    rem.setHouseId(houseId);
                                                    rem.setOrgId(orgId1);
                                                    rem.setBalanceFee(0);
                                                    rem.setCashPledge(0);
                                                    rem.setMatchUserId(matchUserId1);
                                                    rem.setLastUpdateTime(date);
                                                    rem.setCreateTime(date);
                                                    rem.setStatus(RemainingStatusEnum.NORMAL.getValue());
                                                    HouseRemaining remSave = houseRemainingRepository.save(rem);


                                                    HouseRemainingRelation remRelation = new HouseRemainingRelation();
                                                    remRelation.setHouseId(houseId);
                                                    remRelation.setRemainingId(remSave.getId());
                                                    remRelation.setCreateTime(date);
                                                    remRelation.setOrgId(orgId1);
                                                    houseRemainingRelationRepository.save(remRelation);
                                                }
                                                if (housePropertyId1 != null && !orgId1.equals(housePropertyId1)) {

                                                    HouseRemaining rem = new HouseRemaining();
                                                    rem.setRemainingType(2);
                                                    rem.setType(muhVO.getLabel());
                                                    rem.setHouseId(houseId);
                                                    rem.setOrgId(housePropertyId1);
                                                    rem.setBalanceFee(0);
                                                    rem.setCashPledge(0);
                                                    rem.setMatchUserId(matchUserId1);
                                                    rem.setLastUpdateTime(date);
                                                    rem.setCreateTime(date);
                                                    rem.setStatus(RemainingStatusEnum.NORMAL.getValue());
                                                    HouseRemaining remSave = houseRemainingRepository.save(rem);


                                                    HouseRemainingRelation remRelation = new HouseRemainingRelation();
                                                    remRelation.setHouseId(houseId);
                                                    remRelation.setRemainingId(remSave.getId());
                                                    remRelation.setCreateTime(date);
                                                    remRelation.setOrgId(housePropertyId1);
                                                    houseRemainingRelationRepository.save(remRelation);
                                                }
                                            }
                                            if (muhVO.getLabel() == 2) {
                                                List<DepartmentRemainingRef> depRemainingRef = departmentRemainingRefRepository.findByDepIdAndHouseId(muhVO.getId(), houseId);
                                                // 账户不存在
                                                if (depRemainingRef.isEmpty()) {
                                                    if (orgId1 != null) {
                                                        DepartmentRemaining depRem = departmentRemainingRepository.findByDepIdAndOrgId(muhVO.getId(), orgId1);
                                                        if (depRem == null) {
                                                            DepartmentRemaining departmentRemaining = new DepartmentRemaining();
                                                            departmentRemaining.setDepId(muhVO.getId());
                                                            departmentRemaining.setDepName(muhVO.getCompanyName());
                                                            departmentRemaining.setHouseId(houseId);
                                                            departmentRemaining.setOrgId(orgId1);
                                                            departmentRemaining.setBalanceFee(0);
                                                            departmentRemaining.setCashPledge(0);
                                                            departmentRemaining.setLastUpdateTime(date);
                                                            departmentRemaining.setCreateTime(date);
                                                            departmentRemaining.setStatus(1);
                                                            depRem = departmentRemainingRepository.save(departmentRemaining);
                                                        }

                                                        DepartmentRemainingRef remainingRef = new DepartmentRemainingRef();
                                                        remainingRef.setDepId(muhVO.getId());
                                                        remainingRef.setDepName(muhVO.getCompanyName());
                                                        remainingRef.setOrgId(orgId1);
                                                        remainingRef.setHouseId(houseId);
                                                        remainingRef.setRemainingId(depRem.getId());
                                                        remainingRef.setCreateTime(date);
                                                        remainingRef.setRentWithholdStatus(1);
                                                        remainingRef.setElseWithholdStatus(1);
                                                        departmentRemainingRefRepository.save(remainingRef);
                                                    }
                                                    if (housePropertyId1 != null && !orgId1.equals(housePropertyId1)) {
                                                        DepartmentRemaining depRem = departmentRemainingRepository.findByDepIdAndOrgId(muhVO.getId(), housePropertyId1);
                                                        if (depRem == null) {
                                                            DepartmentRemaining departmentRemaining = new DepartmentRemaining();
                                                            departmentRemaining.setDepId(muhVO.getId());
                                                            departmentRemaining.setDepName(muhVO.getCompanyName());
                                                            departmentRemaining.setHouseId(houseId);
                                                            departmentRemaining.setOrgId(housePropertyId1);
                                                            departmentRemaining.setBalanceFee(0);
                                                            departmentRemaining.setCashPledge(0);
                                                            departmentRemaining.setLastUpdateTime(date);
                                                            departmentRemaining.setCreateTime(date);
                                                            departmentRemaining.setStatus(1);
                                                            depRem = departmentRemainingRepository.save(departmentRemaining);
                                                        }
                                                        DepartmentRemainingRef remainingRef = new DepartmentRemainingRef();
                                                        remainingRef.setDepId(muhVO.getId());
                                                        remainingRef.setDepName(muhVO.getCompanyName());
                                                        remainingRef.setOrgId(housePropertyId1);
                                                        remainingRef.setHouseId(houseId);
                                                        remainingRef.setRemainingId(depRem.getId());
                                                        remainingRef.setCreateTime(date);
                                                        remainingRef.setRentWithholdStatus(1);
                                                        remainingRef.setElseWithholdStatus(1);
                                                        departmentRemainingRefRepository.save(remainingRef);
                                                    }
                                                }
                                            }

                                        }
                                    }
                                }

                                //	新增流动人员数据
                                //	类型：1租户 2成员 3房屋管理员 4房管员 (3房屋管理员和4房管员不用记录)
                                if (communityHouseUser.getType() == 1 || communityHouseUser.getType() == 2) {
                                    UserFloatingPopulationRecord record = new UserFloatingPopulationRecord();
                                    record.setUserId(communityHouseUser.getUserId());
                                    record.setUserPhone(communityHouseUser.getMobile());
                                    record.setUserName(communityHouseUser.getName());
                                    record.setHouseId(communityHouseUser.getCommunityHouseId());
                                    record.setOrgId(house.getOrgId());
                                    record.setType(UserFloatingPopulationRecord.RECORD_TYPE_CHECK_IN);
                                    record.setCreateBy(token.getId());
                                    record.setCreateTime(new Date());
                                    userFloatingPopulationRecordService.insertUserFloatingPopulationRecord(record);
                                }
                            }
                        }

                    }

                }


                // 删除房屋管理员
                for (String houseId : houseIds) {
                    List<CommunityHouseUser> byCommunityHouseIdAndStatusAndType = communityHouseUserRepository.findByCommunityHouseIdAndStatusAndType(houseId, 1, 3);
                    if (byCommunityHouseIdAndStatusAndType != null && !byCommunityHouseIdAndStatusAndType.isEmpty()) {
                        deleteUserManager(accessToken, byCommunityHouseIdAndStatusAndType.get(0).getId());
                    }
                }

                // List<CommunityHouseUserVO> voList = new ArrayList<>();
                for (CommunityHouseUser communityHouseUser : saveOrEditVO.getCommunityHouseUsers()) {
                    CommunityHouseUserVO vo = convertToVO(communityHouseUser);
                    voList.add(vo);
                }
                // 待办事项
                backlogItemList(backlogItemList);
                return ResultBean.successfulResult(voList);
            }
        } else {
            return ResultBean.failedResultWithMsg("配租方式不能为空");
        }
    }

    @Transactional
    public ResultBean<Object> addOrEditUser(String accessToken, SaveOrEditVO saveOrEditVO) {
        Date date = new Date();
        String systemUser = redisService.getSystemUser();
        MatchUserHouseVO muhVO = saveOrEditVO.getMatchUserHouseVO();
        if (muhVO == null) {
            return ResultBean.failedResultWithMsg("租户信息有误");
        }

        if (muhVO.getLabel() == null) {
            return ResultBean.failedResultWithMsg("承租人类型不能为空");
        }
        if (saveOrEditVO.getMatchType() == null) {
            saveOrEditVO.setMatchType(1);
        }
        List<SmartLock> lockStatus = smartLockRepository.findByHouseIdAndStatus(saveOrEditVO.getHouseIds(), 1);
        if (CollectionUtil.isEmpty(lockStatus)) {
            Integer errorCode = Convert.toInt(StatusCode.ERROR_CODE_10001.getErrorCode());
            throw new BizException(errorCode, "房屋未绑定智能锁");
        }

        List<CommunityHouseUserVO> voList = new ArrayList<>();


        // 查询需去重的手机号码
        String mobileSql = "SELECT distinct tt.mobile FROM ("
                + "SELECT hu.mobile, hu.card_number FROM saas_community_house_user hu WHERE hu.type = 2 AND hu.status = 1 "
                + "UNION ALL "
                + "SELECT hu.mobile, hu.card_number FROM saas_community_house_user hu LEFT JOIN m_match_user_house uh ON hu.community_house_id = uh.house_id "
                + "WHERE uh.label = 1 AND hu.status = 1 ) tt";


        List<CommunityHouseUser> matchUsers = jdbcTemplate.query(mobileSql, new BeanPropertyRowMapper<>(CommunityHouseUser.class));
        Map<String, CommunityHouseUser> mobileMap = matchUsers.stream().collect(Collectors.toMap(CommunityHouseUser::getMobile, CommunityHouseUser -> CommunityHouseUser));

        String cardSql = "SELECT distinct tt.card_number FROM ("
                + "SELECT hu.mobile, hu.card_number FROM saas_community_house_user hu WHERE hu.type = 2 AND hu.status = 1 "
                + "UNION ALL "
                + "SELECT hu.mobile, hu.card_number FROM saas_community_house_user hu LEFT JOIN m_match_user_house uh ON hu.community_house_id = uh.house_id "
                + "WHERE uh.label = 1 AND hu.status = 1 ) tt";
        List<CommunityHouseUser> cardUsers = jdbcTemplate.query(cardSql, new BeanPropertyRowMapper<>(CommunityHouseUser.class));
        Map<String, CommunityHouseUser> cardMap = cardUsers.stream().filter(ff -> StringUtils.isNotBlank(ff.getCardNumber())).collect(Collectors.toMap(CommunityHouseUser::getCardNumber, CommunityHouseUser -> CommunityHouseUser));

        // 查询承租人库是否存在此承租人
        Optional<CommunityHouseUser> matchUserOpt = saveOrEditVO.getCommunityHouseUsers().stream()
                .filter(i -> i.getType() == 1).findFirst();
        log.info("saveOrEdit matchUserOpt={}", JSON.toJSONString(matchUserOpt));
        CommunityHouseUser cmatchUser = null;

        if (matchUserOpt.isPresent()) {
            cmatchUser = matchUserOpt.get();
        }
        MatchUser mUser = null;
        // 承租人库不存在该承租人
        if (ObjectUtil.isNotEmpty(cmatchUser)) {
            // 查询租户对应的APP账户信息
            AppUser appUser = appUserRepository.findByPhoneAndTypeAndStatus(cmatchUser.getMobile(), UserLoginTypeEnum.CONSUMER.getValue(), 1);
            mUser = matchUserRepository.findByMatchUserId(appUser.getId());
            if (ObjectUtil.isEmpty(mUser)) {
                // 新增承租人库
                MatchUser matchUser = new MatchUser();
                matchUser.setMatchUserId(appUser != null ? appUser.getId() : null);
                matchUser.setName(appUser != null ? appUser.getName() : cmatchUser.getName());
                matchUser.setPhone(cmatchUser.getMobile());
                matchUser.setDeleteStatus(false);
                matchUser.setCraeteUserId(systemUser);
                matchUser.setCreateTime(date);
                matchUser.setLastUpdateTime(date);
                mUser = matchUserRepository.save(matchUser);
            }

        }
        // 如果是批量添加的
        String[] houseIds = muhVO.getHouseId().split(",");
        List<MatchUserLockAuthor> uList = new ArrayList<>();
        for (int i = 0; i < houseIds.length; i++) {
            // 获取房屋id,设置房屋为已出租状态
            // String voHouseId = muhVO.getHouseId();
            Optional<House> byId1 = houseRepository.findById(houseIds[i]);

            // 获取房屋类型：性质:1公租房、2廉租房、3商品房、4经济适用房、5其它
            Integer houseNature = byId1.get().getHouseNature();
            // 公租房需要去重
            if (houseNature == 1 || houseNature == 2) {
                for (CommunityHouseUser communityHouseUser : saveOrEditVO.getCommunityHouseUsers()) {
                    // 新增
                    if (communityHouseUser.getId() == null) {
                        List<CommunityHouseUser> entity = communityHouseUserRepository.findByMobileAndStatus(communityHouseUser.getMobile(), 1);
                        // if (mobileMap.get(communityHouseUser.getMobile()) != null) {
                        //	return ResultBean
                        //			.failedResultWithMsg("手机：" + communityHouseUser.getMobile() + "，已绑定其它房产，不能重复添加");
                        //}

                        // if(StringUtils.isNoneBlank(communityHouseUser.getCardNumber())){
                        //	//List<CommunityHouseUser> entity2 = communityHouseUserRepository.findByCardNumberAndStatus(communityHouseUser.getCardNumber(), 1);
                        //	if (cardMap.get(communityHouseUser.getCardNumber()) != null) {
                        //		return ResultBean.failedResultWithMsg(
                        //				"身份证：" + communityHouseUser.getCardNumber() + "，已绑定其它房产，不能重复添加");
                        //	}
                        //}
                        // 如果是在出租房住的，还能再进保障房入住
                        if (!entity.isEmpty()) {
                            for (CommunityHouseUser houseUser : entity) {
                                String communityHouseId = houseUser.getCommunityHouseId();
                                List<House> byIdAndStatus = houseRepository.findByIdAndStatus(communityHouseId, 1);
                                if (!byIdAndStatus.isEmpty()) {
                                    House house = byIdAndStatus.get(0);
                                    Integer houseNature1 = house.getHouseNature();
                                    if (houseNature1 == 1 || houseNature1 == 2) {
                                        return ResultBean.failedResultWithMsg("手机：" + communityHouseUser.getMobile() + "，已绑定其它房产，不能重复添加");
                                    }
                                }
                            }
                        }

                    }

                    // 编辑
                    if (communityHouseUser.getId() != null) {
                        Optional<CommunityHouseUser> houseUserOptional = communityHouseUserRepository
                                .findById(communityHouseUser.getId());
                        CommunityHouseUser houseUser = houseUserOptional.get();
                        if (!houseUser.getMobile().equals(communityHouseUser.getMobile())) {
                            // List<CommunityHouseUser> entity = communityHouseUserRepository.findByMobileAndStatus(communityHouseUser.getMobile(), 1);
                            if (mobileMap.get(communityHouseUser.getMobile()) != null) {
                                return ResultBean.failedResultWithMsg(
                                        "手机：" + communityHouseUser.getMobile() + "，已绑定其它房产，不能重复添加");
                            }
                        }

                        // 验证身份证
                        if (StringUtils.isNotBlank(communityHouseUser.getCardNumber()) && !communityHouseUser.getCardNumber().equals(houseUser.getCardNumber())) {
                            // List<CommunityHouseUser> entity2 = communityHouseUserRepository.findByCardNumberAndStatus(communityHouseUser.getCardNumber(), 1);
                            if (cardMap.get(communityHouseUser.getCardNumber()) != null) {
                                return ResultBean.failedResultWithMsg(
                                        "身份证：" + communityHouseUser.getCardNumber() + "，已绑定其它房产，不能重复添加");
                            }
                        }
                    }
                }
            }
            // 保存设置房屋为已出租状态
            byId1.get().setLeaseStatus(1);
            byId1.get().setMatchType(1);
            houseRepository.save(byId1.get());

            // 查询是否存在设置记录
            // MatchUserLockAuthor byMatchUserStock = matchUserLockAuthorRepository.findByHouseId(houseIds[i]);
            List<MatchUserLockAuthor> byMatchUserStockList = matchUserLockAuthorRepository.findByHouseId(houseIds[i]);
            if (byMatchUserStockList.size() < 1) {
                MatchUserLockAuthor byMatchUserStock = new MatchUserLockAuthor();
                byMatchUserStock.setCreateTime(new Date());
                byMatchUserStock.setOperatorUserId(1l);
                // 同时插入临时密码次数记录
                // 生效年月
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM");
                byMatchUserStock.setEffectiveJulyDate(dateFormat.format(new Date()));
                byMatchUserStock.setHouseId(houseIds[i]);
                // 默认5次
                byMatchUserStock.setAuthorNumber(5);
                // 默认1天
                byMatchUserStock.setPasswordValidity(1);
                byMatchUserStock.setUseNumber(0);
                // Long matchId = cmatchUser.getMatchId();
                if (cmatchUser == null && mUser != null && mUser.getId() != null) {
                    byMatchUserStock.setMatchUserStockId(mUser.getId() + "");
                } else if (cmatchUser != null) {
                    byMatchUserStock.setMatchUserStockId(cmatchUser.getMatchId() + "");
                }

                byMatchUserStock.setLastUpdateTime(new Date());
                uList.add(byMatchUserStock);
            }
        }
        matchUserLockAuthorRepository.saveAll(uList);

        //-------------------------------特殊关系(儿子、女儿)处理-----------------------------------
        // 编辑时由于特殊关系的手机号码增加了后缀，到时无法编辑保存，优化如下：
        List<CommunityHouseUser> communityHouseUsers = saveOrEditVO.getCommunityHouseUsers();
        List<Long> ids = saveOrEditVO.getCommunityHouseUsers().stream().filter(s -> s.getId() != null).map(t -> t.getId()).collect(Collectors.toList());
        if (ids != null && !ids.isEmpty()) {
            List<CommunityHouseUser> chuList = communityHouseUserRepository.findByIdIn(ids);
            for (CommunityHouseUser chu : chuList) {
                for (CommunityHouseUser vo : saveOrEditVO.getCommunityHouseUsers()) {
                    if (vo.getId() != null && chu.getId().intValue() == vo.getId().intValue()) {
                        // 编辑时返回的数据，去掉后缀，保存时恢复原数据的后缀，而后继续后续逻辑处理(手机号码是不可编辑的，所以可以这样处理)
                        if (chu.getMobile().contains("_")) {
                            vo.setMobile(chu.getMobile());
                        }

                        // 特殊关系编辑时不能修改关系类型
                        if (chu.getRelationTag() != null && vo.getRelationTag() != null && (chu.getRelationTag() == 3 || chu.getRelationTag() == 5) && vo.getRelationTag() != chu.getRelationTag()) {
                            return ResultBean.failedResultWithMsg("特殊关系(儿子、女儿)同住人，不能修改关系!");
                        }
                    }
                }
            }
        }

        int count = 0;
        // 如果是编辑，保持后缀有序生成
        for (CommunityHouseUser vo : saveOrEditVO.getCommunityHouseUsers()) {
            if (vo.getMobile().contains("_")) {
                String suffixCount = vo.getMobile().substring(vo.getMobile().indexOf("_") + 1);
                if (Integer.parseInt(suffixCount) > count) {
                    count = Integer.parseInt(suffixCount);
                }
            }
        }
        count++;

        // 特殊关系的同住人，如果手机号码与承租人相同，重置同住人手机号码，增加后缀（确保手机号字段唯一）
        for (CommunityHouseUser chu : saveOrEditVO.getCommunityHouseUsers()) {
            for (CommunityHouseUser vo : saveOrEditVO.getCommunityHouseUsers()) {
                // 1妻子、2丈夫、3儿子、4儿媳、5女儿、6女婿、7父亲、8母亲、9同事、10哥哥、11嫂子、12姐姐、13姐夫、14弟弟、15弟媳、16妹妹、17妹夫、18其他亲属、19朋友、20非亲属
                if (chu.getType() != null
                        && chu.getType() == 1
                        && chu.getMobile().equals(vo.getMobile())
                        && vo.getRelationTag() != null
                        && vo.getType() != null
                        && vo.getType() == 2
                        && (vo.getRelationTag() == 3 || vo.getRelationTag() == 5)) {
                    vo.setMobile(vo.getMobile() + "_" + count);
                    count++;
                }
            }
        }
        //---------------------------------------------------------------------------------------------


        // 验证成员之间手机号码与身份证是否重复
        List<String> mobiles = saveOrEditVO.getCommunityHouseUsers().stream().map(mm -> mm.getMobile()).distinct().collect(Collectors.toList());
        if (mobiles.size() < saveOrEditVO.getCommunityHouseUsers().size()) {
            return ResultBean.failedResultWithMsg("成员手机号码不能重复");
        }

        List<String> cardNumbers1 = saveOrEditVO.getCommunityHouseUsers().stream().filter(mm -> StringUtils.isNotBlank(mm.getCardNumber())).map(mm -> mm.getCardNumber()).collect(Collectors.toList());
        List<String> cardNumbers2 = saveOrEditVO.getCommunityHouseUsers().stream().filter(mm -> StringUtils.isNotBlank(mm.getCardNumber())).map(mm -> mm.getCardNumber()).distinct().collect(Collectors.toList());
        if (cardNumbers1.size() != cardNumbers2.size()) {
            return ResultBean.failedResultWithMsg("成员身份证号码不能重复");
        }

        // 新增租户信息
        for (CommunityHouseUser communityHouseUser : saveOrEditVO.getCommunityHouseUsers()) {
            // 新增
            if (communityHouseUser.getId() == null) {
                // 新增同住人是否给与查看账单标识
                Integer accountStatus = communityHouseUser.getAccountStatus();
                if (accountStatus != null) {
                    if (accountStatus == 1) {
                        communityHouseUser.setAccountStatus(1);
                    } else {
                        communityHouseUser.setAccountStatus(2);
                    }
                }
                // 查看新增的用户是否已经实名认证了，如果已经实名，就用用户实名认证的名字存储
                String mobile = communityHouseUser.getMobile();
                AppUser byPhoneAndStatus = appUserRepository.findByPhoneAndStatusAndCertificationStatusAndType(mobile, 1, 1, UserLoginTypeEnum.CONSUMER.getValue());
                if (byPhoneAndStatus != null) {
                    String name = byPhoneAndStatus.getName();
                    communityHouseUser.setName(name);
                }
                communityHouseUser.setStatus(1);
                communityHouseUser.setOperatorId(systemUser);
                communityHouseUser.setOperatorTime(date);
            }

            // 租户与房屋管理员区分
            if (communityHouseUser.getType() != null && communityHouseUser.getType() != 3) {
                // 查询租户对应的账户信息
                AppUser appUser = appUserRepository.findByPhoneAndTypeAndStatus(communityHouseUser.getMobile(), UserLoginTypeEnum.CONSUMER.getValue(), 1);
                if (appUser != null) {
                    communityHouseUser.setUserId(appUser.getId());
                } else {
                    User user = userRepository.findByMobile(communityHouseUser.getMobile());
                    if (user != null) {
                        communityHouseUser.setUserId(user.getId());
                    }
                }
                communityHouseUser.setUserType(1);

            } else {
                // 企业管理员的账户信息
                User user = userRepository.findByMobile(communityHouseUser.getMobile());
                if (user != null) {
                    communityHouseUser.setUserId(user.getId());
                }
                communityHouseUser.setUserType(2);
            }
            communityHouseUser.setChangeLabel(1);
        }

        List<BacklogItemVo> backlogItemList = new ArrayList<>();
        for (String houseId : houseIds) {
            // 先查一遍数据库中是否有该承租人和房屋的关系，根据房屋id查询，有就更新
            List<MatchUserHouse> byHouseList = matchUserHouseRepository.findByHouseId(houseId);
            MatchUserHouse matchUserHouse = null;
            MatchUserHouseVO matchUserHouseVO = saveOrEditVO.getMatchUserHouseVO();
            if (byHouseList == null || byHouseList.isEmpty()) {
                matchUserHouse = new MatchUserHouse();
            } else {
                // 更新
                matchUserHouse = byHouseList.get(0);
            }

            if (cmatchUser == null && mUser == null) {
                break;
            }

            if (cmatchUser.getMatchId() == null && mUser != null && mUser.getId() != null) {
                matchUserHouse.setMatchUserStockId(mUser.getId() + "");
            } else if (cmatchUser.getMatchId() != null) {
                matchUserHouse.setMatchUserStockId(cmatchUser.getMatchId() + "");
            }

            matchUserHouse.setHouseId(houseId);
            // List<CommunityHouseUser> users = communityHouseUserRepository.findByCommunityHouseIdAndStatusAndType(houseId, 1, 1);
            // matchUserHouse.setMemberUserId(!users.isEmpty() ? users.get(0).getId() : null);
            matchUserHouse.setLabel(matchUserHouseVO.getLabel());
            matchUserHouse.setCompanyName(matchUserHouseVO.getCompanyName());
            matchUserHouse.setSocialCreditNumber(matchUserHouseVO.getSocialCreditNumber());
            matchUserHouse.setStartDate(matchUserHouseVO.getStartDate());
            matchUserHouse.setEndDate(matchUserHouseVO.getEndDate());
            matchUserHouse.setChargeMode(matchUserHouseVO.getChargeMode());
            matchUserHouse.setCreateTime(new Date());
            // 承租人和房屋关系表
            matchUserHouseRepository.save(matchUserHouse);
        }

        for (String houseId : houseIds) {
            Map<String, Long> orgId = new HashMap<>();

            String residenceCommunityId = null;
            Optional<House> byId = houseRepository.findById(houseId);

            if (byId.isPresent()) {
                House house = byId.get();
                residenceCommunityId = house.getResidenceCommunityId();
                orgId.put("orgId", house.getOrgId());
                orgId.put("housePropertyId", house.getHousePropertyId());
            }
            // 整租房产添加成员如果有绑定智能锁的情况下添加智能锁信息
            List<SmartLock> lockList = smartLockRepository.findByHouseIdAndStatus(houseId, 1);
            // 合租房产添加成员如果有绑定智能锁的情况下添加智能锁信息
            List<House> byIdAndStatus = houseRepository.findByIdAndStatus(houseId, 1);
            String housemateId = null;
            if (byIdAndStatus.size() > 0) {
                housemateId = byIdAndStatus.get(0).getHousemateId();
            }
            // 获取合租房产的智能锁信息
            List<SmartLock> lockSubHouseList = smartLockRepository.findByHouseIdAndStatus(housemateId, 1);
            if (!lockList.isEmpty() || !lockSubHouseList.isEmpty()) {// 已安装锁
                SmartLock smartLock = lockList.size() > 0 ? lockList.get(0) : lockSubHouseList.get(0);
                Long lockId = lockList.size() > 0 ? lockList.get(0).getId() : lockSubHouseList.get(0).getId();
                // 租户id
                List<CommunityHouseUser> tenantList = saveOrEditVO.getCommunityHouseUsers().stream()
                        .filter(c -> c.getType() == 1).collect(Collectors.toList());
                String matchUserId = null;
                String matchUserName = null;
                if (!tenantList.isEmpty()) {
                    matchUserId = tenantList.get(0).getUserId();
                    matchUserName = tenantList.get(0).getName();
                }

                // 更新锁承租人id、姓名
                smartLock.setMatchUserId(matchUserId);
                smartLock.setMatchUserName(matchUserName);
                smartLockRepository.save(smartLock);
                for (CommunityHouseUser communityHouseUser : saveOrEditVO.getCommunityHouseUsers()) {
                    Long id = communityHouseUser.getId();
                    String name = communityHouseUser.getName();
                    String mobile = communityHouseUser.getMobile();

                    communityHouseUser.setCommunityHouseId(houseId);
                    communityHouseUser.setCommunityId(residenceCommunityId);
                    if (id == null) {// 新增
                        CommunityHouseUser entity = new CommunityHouseUser();
                        BeanUtils.copyProperties(communityHouseUser, entity);
                        // 新增添加成员的时候，如果用户已经实名了，需要存在用户的身份证号和人脸照 xiaolong20230330
                        AppUser byPhoneAndStatusAndCertificationStatus = appUserRepository.findByPhoneAndStatusAndCertificationStatusAndType(mobile, 1, 1, UserLoginTypeEnum.CONSUMER.getValue());
                        if (byPhoneAndStatusAndCertificationStatus != null) {
                            String facePic = byPhoneAndStatusAndCertificationStatus.getFacePic();
                            String cardNumber = byPhoneAndStatusAndCertificationStatus.getCardNumber();
                            entity.setHumanFaceImage(facePic);
                            entity.setCardNumber(cardNumber);
                        }
                        CommunityHouseUser save = communityHouseUserRepository.save(entity);
                        // 产生待办事项, type: 1新增同住人  2 新增承租人 3 删除同住人  4 删除承租人
                        Integer type = save.getType() == 1 ? 2 : 1;
                        BacklogItemVo backlogItemVo = new BacklogItemVo();
                        backlogItemVo.setCommunityHouseId(houseId);// 房产id
                        backlogItemVo.setName(communityHouseUser.getName());// 人员名称
                        backlogItemVo.setOperatorId(systemUser);// 操作人id
                        backlogItemVo.setId(save.getId());// 房产成员信息登记表明细表id   saas_community_house_user
                        backlogItemVo.setType(type);// 1新增同住人  2 新增承租人 3 删除同住人  4 删除承租人
                        backlogItemVo.setPhone(save.getMobile());// 手机号
                        backlogItemList.add(backlogItemVo);

                        // backlogItem(houseId, token.getEnterpriseId(), communityHouseUser.getName(), token.getId(), save.getId(), type);

                        SmartLockAuth auth = new SmartLockAuth();
                        auth.setLockId(lockId);
                        auth.setHouseId(smartLock.getHouseId());
                        auth.setBindType(0);// 单位
                        auth.setMatchUserId(matchUserId);
                        auth.setAuthorUserId(communityHouseUser.getUserId());
                        if (communityHouseUser.getType() == 1) {
                            auth.setUserType(1);
                        } else {
                            auth.setUserType(2);
                        }
                        auth.setUserName(name);
                        auth.setMobile(mobile);

                        if (smartLock.getMechineStatus() == 2) {
                            auth.setPwdStatus(2);
                            auth.setFingerprintStatus(2);
                            auth.setCardStatus(2);
                            auth.setCpuStatus(2);
                            auth.setBleStatus(2);
                            auth.setFaceStatus(2);
                        } else {
                            auth.setPwdStatus(0);
                            auth.setFingerprintStatus(0);
                            auth.setCardStatus(0);
                            auth.setCpuStatus(0);
                            auth.setBleStatus(0);
                            auth.setFaceStatus(0);
                        }
                        auth.setRelationTag(communityHouseUser.getRelationTag());
                        auth.setCreateTime(date);
                        auth.setCommunityUserId(save.getId());
                        // 新增合租房屋子房屋Id
                        auth.setSubHouseId(communityHouseUser.getCommunityHouseId());
                        // 新增房屋号
                        List<House> byIdAndStatus1 = houseRepository.findByIdAndStatus(communityHouseUser.getCommunityHouseId(), 1);
                        String num = null;
                        if (byIdAndStatus1.size() > 0) {
                            num = byIdAndStatus1.get(0).getRoomNumber();
                        }
                        auth.setRoomNumber(num);
                        smartLockAuthRepository.save(auth);

                        Long orgId1 = orgId.get("orgId");
                        Long housePropertyId1 = orgId.get("housePropertyId");
                        ArrayList<Long> orgIds = new ArrayList<>();
                        orgIds.add(orgId1);
                        orgIds.add(housePropertyId1);
                    }

                    if (id != null) {// 编辑
                        // 首先查询数据库，如果数据库中的数据不为null或者""，再进入方法
                        // 判断如果humanFaceImage 为 null或者为""，就调用oss中删除文件的操作
                        if (StringUtils.isBlank(communityHouseUser.getHumanFaceImage())) {
                            // 根据userId先查到数据
                            List<CommunityHouseUser> byUserIdAndStatus = communityHouseUserRepository
                                    .findByIdAndStatus(communityHouseUser.getId(), 1);
                            byUserIdAndStatus.forEach(item -> {
                                if (StringUtils.isNotBlank(item.getHumanFaceImage())) {
                                    ossService.deleteObject(null, item.getHumanFaceImage());
                                }
                            });
                        }
                        String humanFaceImage = communityHouseUser.getHumanFaceImage();
                        if (humanFaceImage != null) {
                            humanFaceImage = humanFaceImage.replace(ossBucketUrl, "");
                        }
                        communityHouseUser.setHumanFaceImage(humanFaceImage);
                        communityHouseUserRepository.save(communityHouseUser);

                        SmartLockAuth auth = smartLockAuthRepository.findByCommunityUserId(id);
                        auth.setMatchUserId(matchUserId);
                        auth.setAuthorUserId(communityHouseUser.getUserId());
                        auth.setUserName(name);
                        auth.setMobile(mobile);
                        auth.setRelationTag(communityHouseUser.getRelationTag());
                        if (communityHouseUser.getType() == 1) {
                            auth.setUserType(1);
                        } else if (communityHouseUser.getType() == 2) {
                            auth.setUserType(2);
                        } else if (communityHouseUser.getType() == 3) {
                            auth.setUserType(3);// 房屋管理员
                        } else {
                            auth.setUserType(4);// 房管员
                        }
                        smartLockAuthRepository.save(auth);
                    }
                }
            }

        }


        // 删除房屋管理员
        for (String houseId : houseIds) {
            List<CommunityHouseUser> byCommunityHouseIdAndStatusAndType = communityHouseUserRepository.findByCommunityHouseIdAndStatusAndType(houseId, 1, 3);
            if (byCommunityHouseIdAndStatusAndType != null && !byCommunityHouseIdAndStatusAndType.isEmpty()) {
                deleteUserManager(accessToken, byCommunityHouseIdAndStatusAndType.get(0).getId());
            }
        }

        // List<CommunityHouseUserVO> voList = new ArrayList<>();
        for (CommunityHouseUser communityHouseUser : saveOrEditVO.getCommunityHouseUsers()) {
            CommunityHouseUserVO vo = convertToVO(communityHouseUser);
            voList.add(vo);
        }
        // 待办事项
        backlogItemList(backlogItemList);
        return ResultBean.successfulResult(voList);
    }

    ;


    /**
     * 新增/修改 房屋管理员
     *
     * @param accessToken
     * @param saveOrEditVO 以安装智能锁 新增 房屋先新增智能锁的授权记录 修改 先将oss存储的人脸头像信息删除 再将智能锁的授权记录更改
     *                     未安装智能锁 新增房屋信息为房屋管理员
     */
    public void saveHouseManager(String accessToken, SaveOrEditVO saveOrEditVO) {
        TokenRedisVo token = redisService.findTokenVo(accessToken);
        Date date = new Date();

        // 新增租户信息
        for (CommunityHouseUser communityHouseUser : saveOrEditVO.getCommunityHouseUsers()) {
            // 新增
            if (communityHouseUser.getId() == null) {
                communityHouseUser.setStatus(1);
                communityHouseUser.setOperatorId(token.getId());
                communityHouseUser.setOperatorTime(date);
            }

            // 企业管理员的账户信息
            User user = userRepository.findByMobile(communityHouseUser.getMobile());
            if (user != null) {
                communityHouseUser.setUserId(user.getId());
            }
            communityHouseUser.setUserType(2);
            communityHouseUser.setChangeLabel(1);
        }


        // 未安装锁用户
        List<CommunityHouseUser> list = new ArrayList<>();
        // 获取参数中的房产id
        String[] houseIds = saveOrEditVO.getCommunityHouseUsers().get(0).getCommunityHouseId().split(",");
        for (String houseId : houseIds) {
            // 获取房产所在小区id
            String residenceCommunityId = null;
            Optional<House> byId = houseRepository.findById(houseId);
            if (byId.isPresent()) {
                residenceCommunityId = byId.get().getResidenceCommunityId();
            }

            // 当前房屋的智能锁安装记录
            List<SmartLock> lockList = smartLockRepository.findByHouseId(houseId);
            if (!lockList.isEmpty()) {// 已安装锁
                SmartLock smartLock = lockList.get(0);
                Long lockId = smartLock.getId();

                // 承租人id
                List<CommunityHouseUser> tenantList = saveOrEditVO.getCommunityHouseUsers().stream().filter(c -> c.getType() == 1).collect(Collectors.toList());
                String matchUserId = null;
                String matchUserName = null;
                if (!tenantList.isEmpty()) {
                    matchUserId = tenantList.get(0).getUserId();
                    matchUserName = tenantList.get(0).getName();
                }

                // 更新锁承租人id、姓名
                smartLock.setMatchUserId(matchUserId);
                smartLock.setMatchUserName(matchUserName);
                smartLock.setMechineStatus(1);
                smartLockRepository.save(smartLock);

                // 设置房产成员信息
                for (CommunityHouseUser communityHouseUser : saveOrEditVO.getCommunityHouseUsers()) {
                    Long id = communityHouseUser.getId();
                    String name = communityHouseUser.getName();
                    String mobile = communityHouseUser.getMobile();

                    communityHouseUser.setCommunityHouseId(houseId);
                    communityHouseUser.setCommunityId(residenceCommunityId);
                    if (id == null) {// 新增
                        CommunityHouseUser save = communityHouseUserRepository.save(communityHouseUser);
                        // 为当前承租人授权智能锁
                        SmartLockAuth auth = new SmartLockAuth();
                        auth.setLockId(lockId);
                        auth.setHouseId(houseId);
                        auth.setBindType(0);// 单位
                        auth.setMatchUserId(matchUserId);
                        auth.setAuthorUserId(communityHouseUser.getUserId());
                        auth.setUserType(3);// 用户类型:1承租人 2同住人 3房屋管理员
                        auth.setUserName(name);
                        auth.setMobile(mobile);
                        auth.setPwdStatus(0);
                        auth.setFingerprintStatus(0);
                        auth.setCardStatus(0);
                        auth.setCpuStatus(0);
                        auth.setBleStatus(0);
                        auth.setCreateTime(date);
                        auth.setCommunityUserId(save.getId());
                        smartLockAuthRepository.save(auth);
                    }

                    if (id != null) {// 编辑承租人
                        // 判断如果humanFaceImage 为 null或者为""，就调用oss中删除文件的操作
                        if (StringUtils.isBlank(communityHouseUser.getHumanFaceImage())) {
                            // 根据userId先查到数据
                            List<CommunityHouseUser> byUserIdAndStatus = communityHouseUserRepository.findByIdAndStatus(communityHouseUser.getId(), 1);
                            byUserIdAndStatus.forEach(item -> {
                                if (StringUtils.isNotBlank(item.getHumanFaceImage())) {
                                    ossService.deleteObject(null, item.getHumanFaceImage());
                                }
                            });
                        }
                        communityHouseUserRepository.save(communityHouseUser);

                        // 修改当前的智能锁授权人记录
                        SmartLockAuth auth = smartLockAuthRepository.findByCommunityUserId(id);
                        auth.setMatchUserId(matchUserId);
                        auth.setAuthorUserId(communityHouseUser.getUserId());
                        auth.setUserName(name);
                        auth.setMobile(mobile);
                        auth.setUserType(3);// 房屋管理员
                        smartLockAuthRepository.save(auth);
                    }
                }
            } else {// 未安装锁
                for (CommunityHouseUser communityHouseUser : saveOrEditVO.getCommunityHouseUsers()) {
                    CommunityHouseUser entity = new CommunityHouseUser();
                    communityHouseUser.setCommunityHouseId(houseId);
                    communityHouseUser.setCommunityId(residenceCommunityId);
                    BeanUtils.copyProperties(communityHouseUser, entity);
                    list.add(entity);
                }
            }
        }
        if (!list.isEmpty()) {
            communityHouseUserRepository.saveAll(list);
        }
    }

    /**
     * 删除房屋管理员
     *
     * @param accessToken
     * @param id
     * @return
     * @author shun
     * @date 2022年6月29日
     */
    public ResultBean<Object> deleteUserManager(String accessToken, Long id) {
        TokenRedisVo token = redisService.findTokenVo(accessToken);
        if (token == null)
            return ResultBean.failedResultOfToken();

        Optional<CommunityHouseUser> optional = communityHouseUserRepository.findById(id);
        CommunityHouseUser houseUser = optional.get();
        Integer type = houseUser.getType();

        SmartLockAuth auth = smartLockAuthRepository.findByCommunityUserId(id);
        if (auth != null) {
            if (type == 1) {// 租户
                // 更新锁承租人id、姓名
                Long lockId = auth.getLockId();
                Optional<SmartLock> lockOptional = smartLockRepository.findById(lockId);
                SmartLock smartLock = lockOptional.get();
                smartLock.setMatchUserId(null);
                smartLock.setMatchUserName(null);
                smartLockRepository.save(smartLock);

                // 更新所有授权用户承租人id
                smartLockAuthRepository.updateMatchUserId(lockId, null);
            }

            Long lockAuthId = auth.getId();
            // 删除用户授权
            lockAppService.delPersonAuth(lockAuthId);
            // 删除表
            smartLockAuthRepository.delete(auth);
        }

        String deleteSql = "UPDATE saas_community_house_user SET status = 2 WHERE id = ?";
        int result = jdbcTemplate.update(deleteSql, id);

        if (result == 1) {
            return ResultBean.successfulResult(null);
        } else {
            return ResultBean.failedResultWithStatus(StatusCode.ERROR_CODE_10001);
        }
    }

    @Transactional
    public ResultBean<List<CommunityHouseUserVO>> edit(String accessToken,
                                                       List<CommunityHouseUser> communityHouseUsers) {
        try {
            TokenRedisVo token = redisService.findTokenVo(accessToken);
            if (token == null)
                return ResultBean.failedResultOfToken();

            CommunityHouseUser communityHouseUser = communityHouseUsers.get(0);
            Long id = communityHouseUser.getId();
            String name = communityHouseUser.getName();
            String mobile = communityHouseUser.getMobile();
            Integer type = communityHouseUser.getType();
            String[] split = communityHouseUser.getCommunityHouseId().split(",");
            for (String s : split) {
                if (communityHouseUser.getUserId() != null) {
                    returnMsg(communityHouseUser.getUserId(), s);
                }
            }

            // 编辑时由于特殊关系的手机号码增加了后缀，到时无法编辑保存，优化如下：
            Optional<CommunityHouseUser> userOpt = communityHouseUserRepository.findById(id);
            CommunityHouseUser entity = userOpt.get();
            // 编辑时返回的数据，去掉后缀，保存时恢复原数据的后缀，而后继续后续逻辑处理(手机号码是不可编辑的，所以可以这样处理)
            if (entity.getMobile().contains("_")) {
                communityHouseUser.setMobile(entity.getMobile());
            }

            // 特殊关系编辑时不能修改关系类型
            if (communityHouseUser.getRelationTag() != null && entity.getRelationTag() != null && (entity.getRelationTag() == 3 || entity.getRelationTag() == 5) && entity.getRelationTag() != communityHouseUser.getRelationTag()) {
                return ResultBean.failedResultWithMsg("特殊关系(儿子、女儿)同住人，不能修改关系!");
            }

            // 编辑
            Optional<CommunityHouseUser> houseUserOptional = communityHouseUserRepository.findById(id);
            CommunityHouseUser houseUser = houseUserOptional.get();
            String houseId = houseUser.getCommunityHouseId();
            List<CommunityHouseUser> tenantList = communityHouseUserRepository.findByCommunityHouseIdAndStatusAndType(houseId, 1, 1);

            // 查询租户对应的账户信息
            if (token.getLoginType() == 2) {
                // 查询租户对应的账户信息
                AppUser appUser = appUserRepository.findByPhoneAndTypeAndStatus(mobile, UserLoginTypeEnum.CONSUMER.getValue(), 1);
                // 成员也关联，但是不强制验证
                if (appUser != null) {
                    communityHouseUser.setUserId(appUser.getId());
                }
            } else if (token.getLoginType() == 1) {
                // 企业管理员的账户信息
                User user = userRepository.findByMobile(mobile);
                if (user != null) {
                    communityHouseUser.setUserId(user.getId());
                }
            }

            List<SmartLock> lockList = smartLockRepository.findByHouseId(houseId);
            if (!lockList.isEmpty()) {// 已安装锁
                SmartLock smartLock = lockList.get(0);

                // 租户id
                String matchUserId = null;
                String matchUserName = null;
                if (communityHouseUser.getType() == 1) {
                    matchUserId = communityHouseUser.getUserId();
                    matchUserName = communityHouseUser.getName();
                }
                if (communityHouseUser.getType() == 2 && !tenantList.isEmpty()) {
                    matchUserId = tenantList.get(0).getUserId();
                    matchUserName = tenantList.get(0).getName();
                }

                // 更新锁承租人id、姓名
                smartLock.setMatchUserId(matchUserId);
                smartLock.setMatchUserName(matchUserName);
                smartLockRepository.save(smartLock);

                SmartLockAuth auth = smartLockAuthRepository.findByCommunityUserId(id);
                auth.setMatchUserId(matchUserId);
                auth.setAuthorUserId(communityHouseUser.getUserId());
                auth.setUserName(name);
                auth.setMobile(mobile);
                auth.setRelationTag(houseUser.getRelationTag());
                if (communityHouseUser.getType() == 1) {
                    auth.setUserType(1);
                } else if (communityHouseUser.getType() == 2) {
                    auth.setUserType(2);
                } else {
                    auth.setUserType(3);
                }
                smartLockAuthRepository.save(auth);
            }

            communityHouseUser.setStatus(1);
            communityHouseUser.setOperatorId(houseUser.getOperatorId());
            communityHouseUser.setOperatorTime(houseUser.getOperatorTime());
            communityHouseUser.setChangeLabel(1);
            // 新增修复app端上传人脸照后，一体机可以搜到人员信息，人脸无法识别;解决方法修改图片路径
            String humanFaceImage = communityHouseUser.getHumanFaceImage();
            if (StrUtil.isNotEmpty(humanFaceImage)) {
                humanFaceImage = humanFaceImage.replace(ossBucketUrl, "");
                communityHouseUser.setHumanFaceImage(humanFaceImage);
            }
            communityHouseUserRepository.save(communityHouseUser);

            List<CommunityHouseUserVO> voList = new ArrayList<>();
            CommunityHouseUserVO vo = convertToVO(communityHouseUser);
            voList.add(vo);

            return ResultBean.successfulResult(voList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 删除当前房屋承租人
     *
     * @param accessToken
     * @param id          房屋成员id
     *                    当前房屋有智能锁授权记录  当前成员为承租人时删除智能锁授权记录 删除用户授权 删除智能锁授权表
     *                    产生待办事项   产生删除对应成员待办事项
     *                    修改房产成员信息登记表中状态为删除 承租人与房屋关系表中的承租人重置
     *                    存在承租人的情况   如果数据为空，则删除删除承租人授权信息，发送代办事项，删除承租人，重置智能锁安装记录
     */
    @Transactional
    public ResultBean<Object> delete(String accessToken, Long id) {
        // 验证登陆信息
        TokenRedisVo token = redisService.findTokenVo(accessToken);
        if (token == null)
            return ResultBean.failedResultOfToken();

        // 成员信息
        Optional<CommunityHouseUser> optional = communityHouseUserRepository.findById(id);
        CommunityHouseUser houseUser = optional.get();
        String communityHouseId = houseUser.getCommunityHouseId();
        // 成员类型：1(承租人)租户 2(同住人)成员 3房屋管理员 4房管员
        Integer type = houseUser.getType();
        if (type == 1) {
            return ResultBean.failedResultWithMsg("无法删除承租人！");
        }

        // if ( type == 3) {
        //	return ResultBean.failedResult("无法删除房屋管理员！");
        //}
        // 物业房产：承租人有账单的不能删除
        // List<EstateExpenseBill> estateExpenseBill = estateExpenseBillRepository.findByHouseIdAndPaymentStatusAndAuditStatus(communityHouseId,0,0);
        // List<EstateRentBill> estateRentBill = estateRentBillRepository.findByHouseIdAndPaymentStatusAndAuditStatus(communityHouseId,0,0);
        // if (estateExpenseBill.size() > 0 || estateRentBill.size() > 0) {
        //	return ResultBean.failedResultWithMsg("承租人有账单的不能删除");
        //}
        // 房产成员表的id查出智能锁授权表
        SmartLockAuth auth = smartLockAuthRepository.findByCommunityUserId(id);
        // 根据房屋id得到承租人信息
        String queryMatchUser = "SELECT mus.* FROM m_match_user_house muh\n" +
                "LEFT JOIN m_match_user_stock mus\n" +
                "ON muh.match_user_stock_id = mus.id\n" +
                "WHERE mus.delete_status = 0 ";
        StringBuffer where = new StringBuffer();
        List<Object> args = new ArrayList<>();

        // 当前同住人有房产数据则拼接房产条件
        if (houseUser.getCommunityHouseId() != null) {
            where.append(" and muh.house_id = ? ");
            args.add(houseUser.getCommunityHouseId());
        }

        // 查出当前承租人
        List<MatchUser> matchUsers = jdbcTemplate.query(queryMatchUser + where, new BeanPropertyRowMapper<>(MatchUser.class), args.toArray());

        log.info("删除用户, id={}, auth={}", id, JSON.toJSONString(auth));

        // 当前房屋有智能锁授权记录
        if (auth != null) {
            // 成员类型：1(承租人)租户 2(同住人)成员 3房屋管理员
            if (type == 1) {// 承租人
                // 更新锁承租人id、姓名
                Long lockId = auth.getLockId();
                Optional<SmartLock> lockOptional = smartLockRepository.findById(lockId);
                SmartLock smartLock = lockOptional.get();
                // 删除智能锁承租人记录
                smartLock.setMatchUserId(null);
                smartLock.setMatchUserName(null);
                // 更新当前智能锁记录
                smartLockRepository.save(smartLock);
                // 更新所有授权用户承租人id为空
                smartLockAuthRepository.updateMatchUserId(lockId, null);
            }

            Long lockAuthId = auth.getId();
            // 删除用户授权
            lockAppService.delPersonAuth(lockAuthId);
            // 删除表
            smartLockAuthRepository.delete(auth);
            redisService.deleteAuthTemporaryPwd(auth.getMobile(), auth.getHouseId());
        }


        // 产生待办事项
        // 用户成员：房产成员信息登记表明细、小区名、楼宇名、单元、房号
        String querySql = " SELECT schu.*,sc.name AS communityName,scb.name AS buildName,scbu.name AS unitName,sh.room_number AS roomNumber" +
                " FROM saas_community_house_user schu" +
                " LEFT JOIN saas_house sh" +
                " ON schu.community_house_id = sh.id" +
                " LEFT JOIN saas_community sc\n" +
                " ON sh.residence_community_id = sc.id\n" +
                " LEFT JOIN saas_community_build scb\n" +
                " ON sh.building_num = scb.id\n" +
                " LEFT JOIN saas_community_build_unit scbu\n" +
                " ON sh.unit = scbu.id\n" +
                " WHERE schu.id = ? and schu.status = 1";
        List<CommunityHouseUserVO> query1 = jdbcTemplate.query(querySql, new BeanPropertyRowMapper<>(CommunityHouseUserVO.class), id);
        boolean flag = false;
        if (query1 != null && !query1.isEmpty()) {
            for (CommunityHouseUserVO communityHouseUserVO : query1) {
                // 房屋管理员，不产生待办事项
                // 1承租人 2同住人 3房屋管理员员
                if (communityHouseUserVO.getType() != null && communityHouseUserVO.getType() != 3) {
                    // 是承租人删除承租人，不是删除同住人
                    Integer type2 = communityHouseUserVO.getType() == 1 ? 4 : 3;
                    if (type2 == 3 && !flag) {
                        flag = true;
                    }
                    // 产生待办事项
                    backlogItem(communityHouseUserVO.getCommunityHouseId(), token.getEnterpriseId(), communityHouseUserVO.getName(), token.getId(), communityHouseUserVO.getId(), type2);
                }
            }
        }

        // 修改房产成员信息登记表中状态为删除
        String deleteSql = "UPDATE saas_community_house_user SET status = 2 WHERE id = ?";
        int result = jdbcTemplate.update(deleteSql, id);

        // 删除成员新增人口流动记录
        if (type == 2) {
            UserFloatingPopulationRecord record = new UserFloatingPopulationRecord();
            record.setUserId(houseUser.getUserId());
            record.setUserPhone(houseUser.getMobile());
            record.setUserName(houseUser.getName());
            record.setHouseId(communityHouseId);
            Optional<House> byId = houseRepository.findById(communityHouseId);
            House house = byId.get();
            record.setOrgId(house.getOrgId());
            record.setType(UserFloatingPopulationRecord.RECORD_TYPE_CHECK_OUT);
            record.setCreateBy(token.getId());
            record.setCreateTime(new Date());
            userFloatingPopulationRecordService.insertUserFloatingPopulationRecord(record);
        }

        // 将承租人与房屋关系中的承租人重置
        if (type == 1) {
            // 清空承租人与房屋关系
            matchUserHouseRepository.updateMatchUserId(houseUser.getCommunityHouseId());
        }

        // 存在承租人的情况
        if (matchUsers != null && !matchUsers.isEmpty()) {
            // 发送同住人变更信息给承租人
            if (type == 2 && flag) {
                smsService.sendTemplateSms(matchUsers.get(0).getPhone(), smsConfig.getCohabitantTemplateCode());
            }

            // String resultQuery = "SELECT mus.id,mus.match_user_id AS matchUserStockId,mus.name AS matchUserName" +
            //        " FROM m_match_user_stock mus \n" +
            //        " LEFT JOIN m_match_user_house muh \n" +
            //        " ON mus.id = muh.match_user_stock_id " +
            //        " WHERE muh.house_id not in ('" + houseUser.getCommunityHouseId() + "') and muh.match_user_stock_id = "+matchUsers.get(0).getId()+" and muh.label = 2 ";
            ////查询承租人
            // List<MatchUserHouseVO> query = jdbcTemplate.query(resultQuery, new BeanPropertyRowMapper<>(MatchUserHouseVO.class));
            // if (query.isEmpty()) {
            //	log.info("删除承租人库, id={}, houseId={}", accessToken,matchUsers.get(0).getId(), houseUser.getCommunityHouseId());
            //    //如果数据为空，则删除承租人库
            //    deleteMatch(accessToken,matchUsers.get(0).getId(), houseUser.getCommunityHouseId(), 1);
            //}
        }

        // 删除人脸授权提示
        backlogItemRepository.deleteByHouseIdAndTypeAndMatchUserId(communityHouseId, BacklogItemTypeEnum.FACE_AUTHORIZATION_REMINDER.getValue(), houseUser.getUserId());


        if (result == 1) {
            return ResultBean.successfulResult(null);
        } else {
            return ResultBean.failedResultWithStatus(StatusCode.ERROR_CODE_10001);
        }
    }

    /**
     * 房产成员列表
     *
     * @param accessToken
     * @param searchCondition     搜索条件
     * @param houseId             房产id
     * @param communityId         小区
     * @param buildId             楼栋
     * @param unitId              单元
     * @param roomNumber          房号
     * @param floor               楼层
     * @param name                产权人
     * @param mobile              产权人电话
     * @param type                成员人数
     * @param openPushMessageType 未开门消息推送提醒（0：所有用户信息推送；1：重点关注人群信息推送）
     * @param pageNumber
     * @param pageSize            查询对应房屋成员 企业单位登录显示企业管理房屋成员 普通登录查询名下管辖房屋成员
     */
    public ResultBean<ApiData<CommunityHouseUserVO>> list(String accessToken, Integer determineType, String searchCondition, String houseId,
                                                          String communityId, Long buildId, Long unitId, String roomNumber, Integer floor, String name, String mobile,
                                                          Integer type, String openPushMessageType, Integer pageNumber, Integer pageSize) {

        try {
            // 校验登录信息
            TokenRedisVo token = redisService.findTokenVo(accessToken);
            if (token == null)
                return ResultBean.failedResultOfToken();

            Long enterpriseId = token.getEnterpriseId();
            // 用户对应房屋
            List<Map<String, Object>> communityList = appCommunityService.findCommunity(accessToken).getResultData();

            // 租户信息
            String sql = "SELECT schu.id, sau.certification_status AS certificationStatus,schu.community_house_id AS communityHouseId,schu.community_id AS communityId,schu.type,schu.user_id AS userId,schu.name,schu.mobile,schu.operator_time AS operatorTime,schu.open_push_message_type AS openPushMessageType, \n" +
                    "sc.name AS communityName,sch.`building_num` as buildId,scb.name AS buildName,sch.`unit` as unitId,scbu.name AS unitName,sch.room_number AS roomNumber,sch.floor,sch.house_nature AS houseNature, \n" +
                    "sch.owner_name as ownerName,sch.owner_mobile as ownerMobile ,\n" +
                    "sch.unit_lessee_id AS unitLesseeId, sch.org_id\n" +
                    "FROM saas_community_house_user schu \n" +
                    "LEFT JOIN saas_app_user sau ON sau.id = schu.user_id\n" +
                    "LEFT JOIN saas_house sch ON schu.community_house_id = sch.id \n" +
                    "LEFT JOIN saas_community sc ON schu.community_id = sc.id \n" +
                    "LEFT JOIN saas_community_build scb ON sch.building_num = scb.id \n" +
                    "LEFT JOIN saas_community_build_unit scbu ON sch.unit = scbu.id WHERE schu.status = 1\n" +
                    "UNION ALL \n" +
                    "SELECT u.id, sau.certification_status AS certificationStatus,h.id AS communityHouseId,h.residence_community_id AS communityId,1 AS TYPE,u.match_user_id AS userId,a.name,a.mobile,u.operator_time AS operatorTime,0 AS openPushMessageType,  \n" +
                    "sc.name AS communityName,h.`building_num` as buildId,scb.name AS buildName,h.unit as unitId,scbu.name AS unitName,h.room_number AS roomNumber,h.floor,h.house_nature AS houseNature, \n" +
                    "h.owner_name as ownerName,h.owner_mobile as ownerMobile ,\n" +
                    "h.unit_lessee_id AS unitLesseeId, h.org_id\n" +
                    "FROM saas_house_match_user u \n" +
                    "LEFT JOIN saas_app_user sau ON sau.id = u.match_user_id \n" +
                    "LEFT JOIN saas_house_eligible_apply a ON a.id = u.apply_id\n" +
                    "LEFT JOIN `saas_house` h ON u.house_id = h.`id`\n" +
                    "LEFT JOIN saas_community sc ON h.residence_community_id = sc.id \n" +
                    "LEFT JOIN saas_community_build scb ON h.building_num = scb.id \n" +
                    "LEFT JOIN saas_community_build_unit scbu ON h.unit = scbu.id WHERE u.status = 1 \n" +
                    "UNION ALL \n" +
                    "SELECT u.id, sau.certification_status AS certificationStatus,h.id AS communityHouseId,h.residence_community_id as communityId,2 AS TYPE,NULL AS userId,c.name AS NAME,c.mobile AS mobile,u.operator_time AS operatorTime,0 AS openPushMessageType,  \n" +
                    "sc.name AS communityName,h.`building_num` AS buildId,scb.name AS buildName,h.unit as unitId,scbu.name AS unitName,h.room_number AS roomNumber,h.floor,h.house_nature AS houseNature, \n" +
                    "h.owner_name as ownerName,h.owner_mobile as ownerMobile ,\n" +
                    "h.unit_lessee_id AS unitLesseeId, h.org_id\n" +
                    "FROM saas_house_eligible_apply_cohabit c\n" +
                    "LEFT JOIN `saas_house_match_user` u ON u.apply_id = c.apply_id\n" +
                    "LEFT JOIN saas_app_user sau ON sau.id = u.match_user_id \n" +
                    "LEFT JOIN `saas_house` h ON u.house_id = h.`id`\n" +
                    "LEFT JOIN saas_community sc ON h.residence_community_id = sc.id \n" +
                    "LEFT JOIN saas_community_build scb ON h.building_num = scb.id \n" +
                    "LEFT JOIN saas_community_build_unit scbu ON h.unit = scbu.id WHERE c.status IN (1,4) AND u.status = 1 ";

            String querySql = "select * from ( " + sql + " ) t where 1 = 1";
            String countSql = "select count(1) from ( " + sql + " ) t where 1 = 1";
            Map<String, Object> params = new HashMap<>();
            if (determineType != null && determineType == 1) {
                params.put("limit", pageSize);
                params.put("offset", pageSize * pageNumber);
            }
            ApiData<CommunityHouseUserVO> apiData = new ApiData<>();
            // 登录类型
            Integer loginType = token.getLoginType();
            String userId = token.getId();

            if (loginType == 1) {// 企业用户
                // 根据用户ID查询出用户层级权限
                DepartmentHierarchy hierarchy = departmentHierarchyRepository.findByOrgIdAndStatus(enterpriseId, 1);
                if (hierarchy == null) {
                    return ResultBean.failedResultWithMsg("用户所属机构未设置层级架构");
                }
                // 获取机构ID
                Long id = hierarchy.getId();
                Long orgId = hierarchy.getOrgId();
                // 根据机构ID查询机构消息
                List<DepartmentEnterpriseTagRef> refs = departmentEnterpriseTagRefRepository.findByDepRefId(id);
                // 遍历获取企业标签集合
                List<Long> enterpriseTagIds = refs.stream().map(DepartmentEnterpriseTagRef::getTagId).distinct().collect(Collectors.toList());// 用户企业标签
                // 新增房东只能查看到自己的成员 20230415 xiaolong
                if (enterpriseTagIds.contains(8L)) {
                    querySql += "  AND t.org_id = " + orgId;
                    countSql += "  AND t.org_id = " + orgId;
                } else {
                    // 企业用户拼接小区id
                    if (!communityList.isEmpty()) {
                        StringBuilder communityIds = new StringBuilder("");
                        for (Map<String, Object> map : communityList) {
                            communityIds.append("'" + map.get("communityId") + "'").append(",");
                        }
                        String communityIdsStr = communityIds.toString().substring(0, communityIds.toString().lastIndexOf(","));

                        querySql += "  AND t.communityId IN (  " + communityIdsStr + " )  ";
                        countSql += "  AND t.communityId IN (  " + communityIdsStr + " )  ";
                    } else {
                        apiData.setTotal(0L);
                        apiData.setData(new ArrayList<>());
                        return ResultBean.successfulResult(apiData);
                    }
                }
            } else {// 非企业用户
                // 登录用户名下房屋
                List<String> houseIdList = communityService.getHouseIdList(userId);
                if (houseIdList.isEmpty()) {
                    apiData.setTotal(0L);
                    apiData.setData(new ArrayList<>());
                    return ResultBean.successfulResult(apiData);
                }

                // 查名下管理房屋的成员
                StringBuilder houseIds = new StringBuilder("");
                for (String hId : houseIdList) {
                    houseIds.append("'" + hId + "'").append(",");
                }
                String houseIdsStr = houseIds.toString().substring(0, houseIds.toString().lastIndexOf(","));
                if (StrUtil.isNotBlank(houseIdsStr)) {
                    querySql += "  AND t.communityHouseId IN (  " + houseIdsStr + " )  ";
                    countSql += "  AND t.communityHouseId IN (  " + houseIdsStr + " )  ";
                }
            }

            // 房屋id，小区名称，房号，姓名，手机号
            if (!StringUtils.isEmpty(searchCondition)) {
                params.put("searchCondition", "%" + searchCondition + "%");
                querySql += " AND (t.communityHouseId LIKE :searchCondition OR t.communityName LIKE :searchCondition OR t.roomNumber LIKE :searchCondition OR t.name LIKE :searchCondition OR t.mobile LIKE :searchCondition) ";
                countSql += " AND (t.communityHouseId LIKE :searchCondition OR t.communityName LIKE :searchCondition OR t.roomNumber LIKE :searchCondition OR t.name LIKE :searchCondition OR t.mobile LIKE :searchCondition) ";
            }

            if (!StringUtils.isEmpty(houseId)) {
                params.put("houseId", houseId);
                querySql += " AND t.communityHouseId = :houseId ";
                countSql += " AND t.communityHouseId = :houseId ";
            }

            if (!StringUtils.isEmpty(communityId)) {
                params.put("communityId", communityId);
                querySql += " AND t.communityId = :communityId ";
                countSql += " AND t.communityId = :communityId ";
            }

            if (buildId != null) {
                params.put("buildId", buildId);
                querySql += " AND t.buildId = :buildId ";
                countSql += " AND t.buildId = :buildId ";
            }

            if (unitId != null) {
                params.put("unitId", unitId);
                querySql += " AND t.unitId = :unitId ";
                countSql += " AND t.unitId = :unitId ";
            }

            if (!StringUtils.isEmpty(roomNumber)) {
                params.put("roomNumber", roomNumber);
                querySql += " AND t.roomNumber = :roomNumber ";
                countSql += " AND t.roomNumber = :roomNumber ";
            }

            if (floor != null) {
                params.put("floor", floor);
                querySql += " AND t.floor = :floor ";
                countSql += " AND t.floor = :floor ";
            }

            if (!StringUtils.isEmpty(name)) {
                params.put("name", "%" + name + "%");
                querySql += " AND t.name LIKE :name ";
                countSql += " AND t.name LIKE :name ";
            }

            if (!StringUtils.isEmpty(mobile)) {
                params.put("mobile", "%" + mobile + "%");
                querySql += " AND t.mobile LIKE :mobile ";
                countSql += " AND t.mobile LIKE :mobile ";
            }

            if (type != null) {
                params.put("type", type);
                querySql += " AND t.type = :type ";
                countSql += " AND t.type = :type ";
            }
            if (StrUtil.isNotBlank(openPushMessageType)) {
                params.put("openPushMessageType", openPushMessageType);
                querySql += " AND openPushMessageType = :openPushMessageType ";
                countSql += " AND openPushMessageType = :openPushMessageType ";
            }
            DepartmentHierarchy hierarchy = departmentHierarchyRepository.findByOrgIdAndStatus(enterpriseId, 1);
            // 查询出企业的标签
            enterpriseId = hierarchy.getId();
            List<DepartmentEnterpriseTagRef> refs = departmentEnterpriseTagRefRepository.findByDepRefId(enterpriseId);
            List<Long> enterpriseTagIds = refs.stream().map(DepartmentEnterpriseTagRef::getTagId).distinct().collect(Collectors.toList());// 用户企业标签
            // 判断机构是否带有单位承租人标签
            Long unitLesseeId = null;
            if (enterpriseTagIds.contains(7L)) {
                unitLesseeId = hierarchy.getOrgId();
                params.put("unitLesseeId", unitLesseeId);
                querySql += " and t.unitLesseeId = :unitLesseeId ";
                countSql += " and t.unitLesseeId = :unitLesseeId ";
            }

            querySql += " order by t.operatorTime desc ";
            // 分页
            if (determineType != null && determineType == 1) {
                querySql += " LIMIT :limit OFFSET :offset ";
            }

            // 成员列表
            List<CommunityHouseUserVO> communityHouseUserList = namedParameterJdbcTemplate.query(querySql, params, new BeanPropertyRowMapper<>(CommunityHouseUserVO.class));
            // 成员人数
            Long count = namedParameterJdbcTemplate.queryForObject(countSql, params, Long.class);

            for (CommunityHouseUserVO vo : communityHouseUserList) {
                if (vo.getType() == 1) {
                    vo.setTypeName("承租人");
                } else if (vo.getType() == 2) {
                    vo.setTypeName("同住人");
                } else if (vo.getType() == 3) {
                    vo.setTypeName("房屋管理员");
                } else if (vo.getType() == 4) {
                    vo.setTypeName("房管员");
                }

                // 0是未实名认证
                if (vo.getCertificationStatus() == null) {
                    vo.setCertificationStatus(0);
                }

            }

            // 成员id
            List<Long> collect = communityHouseUserList.stream().map(CommunityHouseUserVO::getId).collect(Collectors.toList());
            // 不仅要根据房子还要根据id
            List<CommunityHouseUser> communityHouseUsers = communityHouseUserRepository.findAllById(collect);
            // 更新房产成员信息登记表信息
            communityHouseUsers.forEach(i -> {
                communityHouseUserList.forEach(item -> {
                    if (i.getId().equals(item.getId())) {
                        // 拼接人脸图片路径 20230308 xiaolong 因为一体机图片路径没有前缀，是自己拼接的
                        String humanFaceImage = i.getHumanFaceImage();
                        if (StrUtil.isNotBlank(humanFaceImage)) {
                            humanFaceImage = ossBucketUrl + humanFaceImage;
                            item.setHumanFaceImage(humanFaceImage);
                        }
                        item.setCardNumber(i.getCardNumber());
                        item.setRelationTag(i.getRelationTag());
                    }

                });
            });
            // 登录用户信息
            AppUser appUser = appUserRepository.findByIdOrEnterpriseUserId(userId, userId);
            String mb = null;
            if (appUser == null) {
                // 企业用户
                User user = userRepository.findById(token.getEnterpriseUserId());
                if (user != null) {
                    mb = user.getMobile();
                }
            } else {
                mb = appUser.getPhone();
            }
            // 手机号查成员信息
            String allHouseSql = " SELECT schu.* FROM saas_community_house_user schu WHERE schu.mobile = ? AND schu.status = 1 AND schu.type = 1";
            List<CommunityHouseUser> huList = jdbcTemplate.query(allHouseSql, new BeanPropertyRowMapper<>(CommunityHouseUser.class), mb);

            // 默认非承租人
            for (CommunityHouseUserVO hh : communityHouseUserList) {
                hh.setMatchStatus(0);
                // 房产相同手机号相同承租人本人
                for (CommunityHouseUser mm : huList) {
                    if (hh.getCommunityHouseId().equals(mm.getCommunityHouseId())) {
                        hh.setMatchStatus(1);
                        // 如果手机号码相同，承租人本人
                        if (hh.getMobile().equals(mb)) {
                            hh.setMatchStatus(2);
                        }
                        break;
                    }
                }
            }

            // 特殊关系同住人，编辑回显时，去掉手机号码后缀（方便回显与保存时手机号码校验）
            for (CommunityHouseUserVO vo : communityHouseUserList) {
                if (vo.getRelationTag() != null && (vo.getRelationTag() == 3 || vo.getRelationTag() == 5) && vo.getMobile().contains("_")) {
                    vo.setMobile(vo.getMobile().substring(0, vo.getMobile().indexOf("_")));
                }
            }

            apiData.setData(communityHouseUserList);
            apiData.setTotal(count);
            return ResultBean.successfulResult(apiData);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public CommunityHouseUserVO convertToVO(CommunityHouseUser communityHouseUser) {
        CommunityHouseUserVO vo = new CommunityHouseUserVO();
        vo.setId(communityHouseUser.getId());
        vo.setCommunityHouseId(communityHouseUser.getCommunityHouseId());
        vo.setCommunityId(communityHouseUser.getCommunityId());
        vo.setType(communityHouseUser.getType());
        if (vo.getType() == 1) {
            vo.setTypeName("承租人");
        } else if (vo.getType() == 2) {
            vo.setTypeName("同住人");
        } else if (vo.getType() == 3) {
            vo.setTypeName("房屋管理员");
        } else if (vo.getType() == 4) {
            vo.setTypeName("房管员");
        }
        vo.setName(communityHouseUser.getName());
        vo.setMobile(communityHouseUser.getMobile());
        vo.setStatus(communityHouseUser.getStatus());
        vo.setOperatorId(communityHouseUser.getOperatorId());
        vo.setOperatorTime(communityHouseUser.getOperatorTime());

        return vo;
    }

    /**
     * 查询房屋成员列表
     *
     * @param communityHouseId 房屋id
     * @return ResultBean<List < CommunityHouseUserVO>>
     */
    public ResultBean<ApiData<ReturnResultVO>> findCommunityHouseUsersbyId(String accessToken, String communityHouseId) {
        try {
            TokenRedisVo token = redisService.findTokenVo(accessToken);
            if (token == null) {
                return ResultBean.failedResultOfToken();
            }
            String phone = token.getPhone();
            ApiData<ReturnResultVO> apiData = new ApiData<>();
            List<ReturnResultVO> data = new ArrayList<>();
            ReturnResultVO returnResultVO = new ReturnResultVO();
            // 登录场景标识：1.PC端登录 2.APP登录
            Integer flag = token.getFlag();
            String[] houseIds = communityHouseId.split(",");

            String result = " SELECT sh.id as communityHouseId,sh.create_time AS operatorTime, sh.residence_community_id AS communityId,sc.name AS communityName,scb.name AS buildName,scbu.name AS unitName,sh.room_number AS roomNumber,sh.owner_name,sh.owner_mobile ";
            String sql = "  FROM saas_house sh\n" +
                    "LEFT JOIN saas_community sc\n" +
                    "ON sh.residence_community_id = sc.id\n" +
                    "LEFT JOIN saas_community_build scb\n" +
                    "ON sh.building_num = scb.id\n" +
                    "LEFT JOIN saas_community_build_unit scbu\n" +
                    "ON sh.unit = scbu.id ";
            StringBuffer where = new StringBuffer(" WHERE 1 = 1 ");
            List<CommunityHouseUserVO> communityHouseUserVOList = new ArrayList<>();
            if (houseIds != null && houseIds.length > 0) {
                List<Object> args = new ArrayList<>();
                args = Arrays.asList(houseIds).stream().map(c -> c.getBytes()).collect(Collectors.toList());
                where.append(" AND sh.id in " + SqlUtils.foreachIn(args.size()));
                // 房屋id查房产成员信息
                List<CommunityHouseUserVO> query = jdbcTemplate.query(result + sql + where, new BeanPropertyRowMapper<>(CommunityHouseUserVO.class), args.toArray());
                for (CommunityHouseUserVO communityHouseUserVO : query) {
                    communityHouseUserVOList.add(communityHouseUserVO);
                }
            }

            // 承租人
            String queryIsLessee = "SELECT muh.* FROM m_match_user_house muh WHERE muh.house_id = ? ";
            List<MatchUserHouseVO> query = jdbcTemplate.query(queryIsLessee, new BeanPropertyRowMapper<>(MatchUserHouseVO.class), houseIds[0]);

            // 查询未删除的房屋成员列表
            String queryMember = "SELECT schu.*, schu.open_push_message_type AS openPushMessageType,schu.card_number AS cardNumber,sau.certification_status AS certificationStatus FROM saas_community_house_user schu\n" +
                    "   LEFT JOIN saas_app_user sau\n" +
                    "   ON schu.user_id = sau.id \n" +
                    "   WHERE schu.community_house_id = ? AND schu.status = 1 AND schu.type != 3";
            List<CommunityHouseUserVO> list = jdbcTemplate.query(queryMember, new BeanPropertyRowMapper<>(CommunityHouseUserVO.class), houseIds[0]);
            // 特殊关系同住人，编辑回显时，去掉手机号码后缀（方便回显与保存时手机号码校验）
            for (CommunityHouseUserVO vo : list) {
                if (vo.getRelationTag() != null && vo.getMobile().contains("_")) {
                    vo.setMobile(vo.getMobile().substring(0, vo.getMobile().indexOf("_")));

                }
                // 拼接人脸图片路径 20230308 xiaolong 因为一体机图片路径没有前缀，是自己拼接的
                String humanFaceImage = vo.getHumanFaceImage();
                if (StringUtils.isNotBlank(humanFaceImage)) {
                    if (StrUtil.startWith(humanFaceImage, "http://") || StrUtil.startWith(humanFaceImage, "https://")) {
                        vo.setHumanFaceImage(humanFaceImage);
                    } else {
                        humanFaceImage = ossBucketUrl + humanFaceImage;
                        vo.setHumanFaceImage(humanFaceImage);
                    }
                }
            }
            // 查询当前用户是否为当前房屋承租人
            boolean resultBean = returnMsg(accessToken, communityHouseId);
            // 如果是同住人只能看到自己的信息
            // 判断是否是承租人，如果是承租人就删除自己，不是就删除承租人和其他同住人
            //	新增房管员应该能看到房屋里面的成员，xiaolong 20230411
            List<CommunityHouseUser> byCommunityHouseIdAndStatusAndMobile = communityHouseUserRepository.findByCommunityHouseIdAndStatusAndMobile(communityHouseId, 1, phone);
            Integer type1 = 0;
            if (!byCommunityHouseIdAndStatusAndMobile.isEmpty()) {
                type1 = byCommunityHouseIdAndStatusAndMobile.get(0).getType();
            }
            if (flag != 1) {
                if (resultBean) {
                    // for (int i = list.size() - 1; i >= 0; i--) {
                    // 	Integer type = list.get(i).getType();
                    // 	if (type == 1 ) {
                    // 		list.remove(i);
                    // 	}
                    // }
                } else if (type1 == 4) {
                    for (int i = list.size() - 1; i >= 0; i--) {
                        Integer type = list.get(i).getType();
                        if (type == 4) {
                            list.remove(i);
                        }
                    }
                } else {
                    for (int i = list.size() - 1; i >= 0; i--) {
                        Integer type = list.get(i).getType();
                        String mobile = list.get(i).getMobile();
                        if (type == 2) {
                            if (!phone.equals(mobile)) {
                                list.remove(i);
                            }
                        } else {
                            list.remove(i);
                        }
                    }
                }
            }

            returnResultVO.setList(list);

            // 更新变更状态
            // for (String houseId : houseIds) {
            //     communityHouseUserRepository.updateChangeLabel(0, houseId);
            // }

            returnResultVO.setCommunityHouseUserVOList(communityHouseUserVOList);// 所有的房屋
            // 如果房产有关联单位承租人机构，就返回单位承租人机构id
            Long unitLesseeId = null;
            List<House> byIdAndStatus1 = houseRepository.findByIdAndStatus(communityHouseId, 1);
            if (!byIdAndStatus1.isEmpty()) {
                unitLesseeId = byIdAndStatus1.get(0).getUnitLesseeId();
            }
            if (query.size() > 0) {

                query.get(0).setId(unitLesseeId);
            }
            returnResultVO.setQuery(query);// 单个承租人

            // 查询当前用户是否为当前房屋承租人
            // boolean resultBean = returnMsg(accessToken, communityHouseId);
            if (resultBean) {
                returnResultVO.setMatchStatus(1);
            } else {
                returnResultVO.setMatchStatus(0);
            }
            // 查询合租房产下发房屋号
            ArrayList<String> roomNumbers = new ArrayList<>();
            List<House> byHousemateIdAndStatus = houseRepository.findByHousemateIdAndStatus(communityHouseId, 1);
            for (House housemateIdAndStatus : byHousemateIdAndStatus) {
                String roomNumber = housemateIdAndStatus.getRoomNumber();
                roomNumbers.add(roomNumber);
            }
            // 查询当前房屋  配租方式：1整租  2合租
            List<House> byIdAndStatus = houseRepository.findByIdAndStatus(communityHouseId, 1);
            if (!byIdAndStatus.isEmpty()) {
                Integer matchType = byIdAndStatus.get(0).getMatchType();
                returnResultVO.setMatchType(matchType);
                returnResultVO.setLeaseStatus(byIdAndStatus.get(0).getLeaseStatus());
            }


            returnResultVO.setRoomNumbers(roomNumbers);
            returnResultVO.setUserCount(list.size());
            data.add(returnResultVO);
            apiData.setData(data);
            return ResultBean.successfulResult(apiData);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 查询承租人库列表
     *
     * @param keyword
     * @return
     * @author shun
     * @date 2022年6月30日
     */
    public ResultBean<ApiData<MatchStockUserVo>> findCommunityHouseUserByNameOrPhone(String keyword) {
        try {
            StringBuffer querysql = new StringBuffer("SELECT st.id, st.name, st.phone, '1' AS TYPE FROM m_match_user_stock st WHERE st.delete_status = 0 ");
            List<Object> args = new ArrayList<>();
            if (StringUtils.isNotBlank(keyword)) {
                querysql.append(" AND (st.name LIKE ? or st.phone LIKE ?) ");
                args.add("%" + keyword + "%");
                args.add("%" + keyword + "%");
            }

            List<MatchStockUserVo> query = jdbcTemplate.query(querysql.toString(), new BeanPropertyRowMapper<>(MatchStockUserVo.class), args.toArray());
            ApiData<MatchStockUserVo> apiData = new ApiData<>();
            apiData.setData(query);
            return ResultBean.successfulResult(apiData);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 根据单位名称和统一社会信用征信模糊查询
     *
     * @param vo
     * @return
     */
    public ResultBean<ApiData<MatchUserHouseVO>> findMatchUserByCompanyNameOrSocialCreditNumber(MatchUserHouseVO vo) {
        try {
            String result = "SELECT * ";
            String SQL = " FROM m_match_user_house muh ";
            // 如果机构名称为空，则不查询出来
            StringBuffer where = new StringBuffer(" WHERE 1=1 and muh.company_name != '' ");
            List<Object> args = new ArrayList<>();
            if (vo != null) {
                // 单位名称
                if (StringUtils.isNotBlank(vo.getCompanyName())) {
                    where.append(" and muh.company_name like ? ");
                    args.add("%" + vo.getCompanyName() + "%");
                }
                // 社会信用代码
                if (StringUtils.isNotBlank(vo.getSocialCreditNumber())) {
                    where.append(" and muh.social_credit_number like ? ");
                    args.add("%" + vo.getSocialCreditNumber() + "%");
                }
            }
            String groupby = "GROUP BY muh.company_name";
            List<MatchUserHouseVO> query = jdbcTemplate.query(result + SQL + where + groupby, new BeanPropertyRowMapper<>(MatchUserHouseVO.class), args.toArray());
            ApiData<MatchUserHouseVO> apiData = new ApiData<>();
            apiData.setData(query);
            return ResultBean.successfulResult(apiData);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 删除承租人
     *
     * @param accessToken
     * @param
     * @return 删除承租人授权信息，发送代办事项，删除承租人，重置智能锁安装记录
     */
    @Transactional
    public ResultBean<Object> deleteMatch(String accessToken, Long id, String houseId, Integer type) {
        log.info("deleteMatch, id={}, houseId={}, type={}", id, houseId, type);
        TokenRedisVo token = redisService.findTokenVo(accessToken);
        if (token == null)
            return ResultBean.failedResultOfToken();

        // 删除承租人授权信息
        String deleteMatchUserLock = "DELETE FROM m_match_user_lock_author WHERE match_user_stock_id=?";
        //  jdbcTemplate.update(deleteMatchUserLock, id);

        if (type == null) {
            Optional<MatchUser> byId = matchUserRepository.findById(id);
            if (byId.isPresent()) {
                // 承租人信息
                MatchUser matchUser = byId.get();
                // 查询承租人登记房产
                List<CommunityHouseUser> byMobileAndStatus = communityHouseUserRepository.findByMobileAndStatus(matchUser.getPhone(), 1);
                Optional<House> byId1 = houseRepository.findById(houseId);
                if (byMobileAndStatus != null && byMobileAndStatus.size() > 0) {
                    // 发送待办事项
                    backlogItem(houseId, byId1.get().getOrgId(), matchUser.getName(), token.getId(), byMobileAndStatus.get(0).getId(), 4);
                }

            }
        }
        // 删除承租人
        String matchUserLock = "DELETE FROM  m_match_user_stock WHERE id=?";
        // 保留承租人信息
        // jdbcTemplate.update(matchUserLock, id);

        // 重置智能锁安装表数据
        String lock = "UPDATE saas_smart_lock SET match_user_id = NULL, match_user_name = NULL, oauth_number = 0, mechine_status = 0, reason = NULL WHERE house_id = ?";
        jdbcTemplate.update(lock, houseId);

        return ResultBean.successfulResultWithMsg("删除成功", null);
    }

    /**
     * 查询当前登录人是否为该房屋承租人
     *
     * @param accessToken
     * @param houseId     查询房屋id
     * @return 返回是否为承租人的标识
     */
    public boolean returnMsg(String accessToken, String houseId) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return false;
            }
            String userId = tokenRedisVo.getId();

            AppUser appUser = appUserRepository.findByIdOrEnterpriseUserId(userId, userId);
            // 获取手机号
            String mobile = null;
            if (appUser == null) {
                User user = userRepository.findById(tokenRedisVo.getEnterpriseUserId());
                if (user != null) {
                    mobile = user.getMobile();
                }
            } else {
                mobile = appUser.getPhone();
            }
            // 房屋id和手机号查承租人
            String sql = " SELECT schu.type FROM saas_community_house_user schu WHERE schu.mobile = ? AND schu.status = 1 AND schu.type = 1 AND schu.community_house_id = ? ";
            List<CommunityHouseUser> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(CommunityHouseUser.class), mobile, houseId);
            if (!query.isEmpty()) {
                // 是承租人
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    /**
     * 租客住户管理-成员信息--导出
     *
     * @param accessToken
     * @param response
     * @throws Exception
     */
    public void communityHouseExport(String accessToken, HttpServletResponse response, Integer determineType, String searchCondition, String houseId, String communityId, Long buildId,
                                     Long unitId, String roomNumber, Integer floor, String name, String mobile, Integer type, Integer pageNumber, Integer pageSize) throws Exception {
        log.info("communityService  communityHouseExport  accessToken={} ", accessToken);
        List<PropertyCommunityHouseVO> data = new ArrayList<>();
        // 表格头
        Map<String, String> map = new LinkedHashMap<>();
        // 文件名
        String fileName = "";
        // 分批查询数据, 每次查询1000条
        ResultBean<ApiData<PropertyCommunityHouseVO>> apiData = propertyCommunityHouseService.listBy(accessToken, determineType, searchCondition, houseId, communityId, buildId, unitId, roomNumber, floor, name, mobile, type, pageNumber, pageSize);

        ApiData<PropertyCommunityHouseVO> resultData = apiData.getResultData();
        List<PropertyCommunityHouseVO> pageData = resultData.getData();

        List<String> collect = pageData.stream().filter(f -> f.getUserCount() != null && f.getUserCount() != 0).map(d -> d.getId()).collect(Collectors.toList());

        // 根据房屋id，查找承租人信息   公租房的单位名称是申请操作单位
        String sql = "SELECT sh.id,muh.company_name AS companyName,schu.name AS matchUserName,schu.mobile AS phone,sc.name AS communityName,b.name AS buildName,u.name AS unitName,sh.room_number AS roomNumber,schu.operator_time AS time1 FROM saas_community_house_user schu\n" +
                "LEFT JOIN saas_house sh\n" +
                "ON sh.id = schu.community_house_id\n" +
                "LEFT JOIN (SELECT mu.house_id,mu.company_name FROM m_match_user_house mu LEFT JOIN saas_house h ON mu.house_id = h.id) muh\n" +
                "ON muh.house_id = sh.id\n" +
                "LEFT JOIN saas_community sc\n" +
                "ON sc.id = sh.residence_community_id\n" +
                "LEFT JOIN saas_community_build b \n" +
                "ON sh.building_num = b.id\n" +
                "LEFT JOIN saas_community_build_unit u\n" +
                "ON sh.unit = u.id\n" +
                "WHERE schu.status = 1 AND sh.id in " + SqlUtils.foreachIn(collect.size()) + "\n" +
                "UNION ALL \n" +
                "SELECT sh.id,d.name AS companyName,shea.name AS matchUserName,shea.mobile AS phone,sc.name AS communityName,b.name AS buildName,u.name AS unitName,sh.room_number AS roomNumber,shea.apply_time AS time1 FROM\n" +
                "saas_house_eligible_apply shea\n" +
                "LEFT JOIN saas_house_match_user shmu\n" +
                "ON shmu.apply_id  = shea.id\n" +
                "LEFT JOIN saas_house sh\n" +
                "ON sh.id = shmu.house_id\n" +
                "LEFT JOIN saas_department d\n" +
                "ON d.id = shea.org_id\n" +
                "LEFT JOIN saas_community sc\n" +
                "ON sc.id = sh.residence_community_id\n" +
                "LEFT JOIN saas_community_build b \n" +
                "ON sh.building_num = b.id\n" +
                "LEFT JOIN saas_community_build_unit u\n" +
                "ON sh.unit = u.id\n" +
                "WHERE shmu.status = 1 and sh.id in " + SqlUtils.foreachIn(collect.size()) + "\n" +
                "UNION ALL\n" +
                "SELECT sh.id,d.name AS companyName,shea.name AS matchUserName,shea.mobile AS phone,sc.name AS communityName,b.name AS buildName,u.name AS unitName,sh.room_number AS roomNumber,shea.apply_time AS time1 FROM\n" +
                "saas_house_eligible_apply_cohabit shea\n" +
                "LEFT JOIN saas_house_match_user shmu\n" +
                "ON shmu.apply_id  = shea.id\n" +
                "LEFT JOIN saas_house_eligible_apply shea1\n" +
                "ON shmu.apply_id  = shea1.id\n" +
                "LEFT JOIN saas_house sh\n" +
                "ON sh.id = shmu.house_id\n" +
                "LEFT JOIN saas_community sc\n" +
                "ON sc.id = sh.residence_community_id\n" +
                "LEFT JOIN saas_community_build b \n" +
                "ON sh.building_num = b.id\n" +
                "LEFT JOIN saas_community_build_unit u\n" +
                "ON sh.unit = u.id\n" +
                "LEFT JOIN saas_department d\n" +
                "ON d.id = shea1.org_id\n" +
                "WHERE sh.id in " + SqlUtils.foreachIn(collect.size()) + "\n";

        List list = new ArrayList();
        for (int i = 0; i < 3; i++) {
            for (String s : collect) {
                list.add(s);
            }
        }

        List<PropertyCommunityHouseVO> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(PropertyCommunityHouseVO.class), list.toArray());

        collect.forEach(item -> {
            query.forEach(i -> {
                if (i.getId().equals(item)) {
                    i.setAddress(i.getCommunityName() + "-" + i.getBuildName() + "-" + i.getUnitName() + "-" + i.getRoomNumber());
                    i.setRegistrationTime(new SimpleDateFormat("yyyy年MM月dd日 hh时mm分ss秒").format(i.getTime1()));
                    data.add(i);
                }
            });
        });

        // 单位名称、单位承租人姓名/个人承租人姓名、手机号码、房屋基本信息（小区-楼栋-单元-房号）
        map.put("单位名称", "companyName");
        map.put("单位承租人姓名/个人承租人姓名", "matchUserName");
        map.put("手机号码", "phone");
        map.put("房屋基本信息", "address");
        map.put("成员登记时间", "registrationTime");

        fileName = "租客住户成员信息导出_" + System.currentTimeMillis();
        Workbook workbook = new Export2Util().getExcelByTemplate(data, map, "importAndExport", "成员信息导出.xlsx", 2);
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        // response.setContentType("application/octet-stream;charset=utf-8");
        // ServletOutputStream outputstream = response.getOutputStream();// 取得输出流
        // File file = file(workbook, fileName);
        // File[] srcFiles = {file};
        // File zipFile = new File(contractTmpDir + "ZipFile.zip");
        // zipFiles(srcFiles, zipFile);
        // byte[] zip = File2byte(zipFile);
        // outputstream.write(zip);
        // outputstream.flush();// 刷数据
        // // 关闭
        // workbook.close();
        DownloadUtil downloadUtil = new DownloadUtil();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        workbook.write(bos);
        downloadUtil.download(bos, response, URLEncoder.encode(fileName + ".xlsx", "utf-8"));
        workbook.close();
    }

    /**
     * 成员管理-成员导出
     *
     * @param accessToken
     * @param response
     * @param determineType
     * @param searchCondition
     * @param houseId
     * @param communityId
     * @param buildId
     * @param unitId
     * @param roomNumber
     * @param floor
     * @param name
     * @param mobile
     * @param type
     * @param pageNumber
     * @param pageSize
     * @throws Exception
     */
    public void memeberHouseExport(String accessToken, HttpServletResponse response, Integer determineType, String searchCondition, String houseId, String communityId, Long buildId,
                                   Long unitId, String roomNumber, Integer floor, String name, String mobile, Integer type, String openPushMessageType, Integer pageNumber, Integer pageSize) throws Exception {
        log.info("communityService  communityHouseExport  accessToken={} ", accessToken);
        List<CommunityHouseUserVO> data = new ArrayList<>();
        // 表格头
        Map<String, String> map = new LinkedHashMap<>();
        // 文件名
        String fileName = "";

        ResultBean<ApiData<CommunityHouseUserVO>> apiData = list(accessToken, determineType, searchCondition, houseId, communityId, buildId, unitId, roomNumber, floor, name, mobile, type, openPushMessageType, pageNumber, pageSize);
        ApiData<CommunityHouseUserVO> resultData = apiData.getResultData();
        List<CommunityHouseUserVO> pageData = resultData.getData();
        // List<String> collect = pageData.stream().filter(distinctByKey())map(CommunityHouseUserVO::getCommunityHouseId).collect(Collectors.toList());

        // List<String> collect = pageData.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(CommunityHouseUserVO::getCommunityHouseId))), ArrayList::new)).stream().map(CommunityHouseUserVO::getCommunityHouseId).collect(Collectors.toList());
        // for (String s : collect) {
        //     System.out.println(s);
        // }

        // pageData.stream().map(CommunityHouseUserVO::getCommunityHouseId).collect(Collectors.toList());

        // 根据房屋id，查找承租人信息   公租房的单位名称是申请操作单位
     /*   String sql = "SELECT sh.id,muh.company_name AS companyName,schu.name AS matchUserName,schu.mobile AS phone,sc.name AS communityName,b.name AS buildName,u.name AS unitName,sh.room_number AS roomNumber,schu.operator_time AS time1 FROM saas_community_house_user schu\n" +
                "LEFT JOIN saas_house sh\n" +
                "ON sh.id = schu.community_house_id\n" +
                "LEFT JOIN (SELECT mu.house_id,mu.company_name FROM m_match_user_house mu LEFT JOIN saas_house h ON mu.house_id = h.id) muh\n" +
                "ON muh.house_id = sh.id\n" +
                "LEFT JOIN saas_community sc\n" +
                "ON sc.id = sh.residence_community_id\n" +
                "LEFT JOIN saas_community_build b \n" +
                "ON sh.building_num = b.id\n" +
                "LEFT JOIN saas_community_build_unit u\n" +
                "ON sh.unit = u.id\n" +
                "WHERE schu.status = 1 AND sh.id in " + SqlUtils.foreachIn(collect.size()) + "\n" +
                "UNION ALL \n" +
                "SELECT sh.id,d.name AS companyName,shea.name AS matchUserName,shea.mobile AS phone,sc.name AS communityName,b.name AS buildName,u.name AS unitName,sh.room_number AS roomNumber,shea.apply_time AS time1 FROM\n" +
                "saas_house_eligible_apply shea\n" +
                "LEFT JOIN saas_house_match_user shmu\n" +
                "ON shmu.apply_id  = shea.id\n" +
                "LEFT JOIN saas_house sh\n" +
                "ON sh.id = shmu.house_id\n" +
                "LEFT JOIN saas_department d\n" +
                "ON d.id = shea.org_id\n" +
                "LEFT JOIN saas_community sc\n" +
                "ON sc.id = sh.residence_community_id\n" +
                "LEFT JOIN saas_community_build b \n" +
                "ON sh.building_num = b.id\n" +
                "LEFT JOIN saas_community_build_unit u\n" +
                "ON sh.unit = u.id\n" +
                "WHERE shmu.status = 1 and sh.id in " + SqlUtils.foreachIn(collect.size()) + "\n" +
                "UNION ALL\n" +
                "SELECT sh.id,d.name AS companyName,shea.name AS matchUserName,shea.mobile AS phone,sc.name AS communityName,b.name AS buildName,u.name AS unitName,sh.room_number AS roomNumber,shea.apply_time AS time1 FROM\n" +
                "saas_house_eligible_apply_cohabit shea\n" +
                "LEFT JOIN saas_house_match_user shmu\n" +
                "ON shmu.apply_id  = shea.id\n" +
                "LEFT JOIN saas_house_eligible_apply shea1\n" +
                "ON shmu.apply_id  = shea1.id\n" +
                "LEFT JOIN saas_house sh\n" +
                "ON sh.id = shmu.house_id\n" +
                "LEFT JOIN saas_community sc\n" +
                "ON sc.id = sh.residence_community_id\n" +
                "LEFT JOIN saas_community_build b \n" +
                "ON sh.building_num = b.id\n" +
                "LEFT JOIN saas_community_build_unit u\n" +
                "ON sh.unit = u.id\n" +
                "LEFT JOIN saas_department d\n" +
                "ON d.id = shea1.org_id\n" +
                "WHERE sh.id in " + SqlUtils.foreachIn(collect.size()) + "\n";

        List list = new ArrayList();
        for (int i = 0; i < 3; i++) {
            for (String s : collect) {
                list.add(s);
            }
        }

        List<PropertyCommunityHouseVO> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(PropertyCommunityHouseVO.class), list.toArray());

        collect.forEach(item -> {
            query.forEach(i -> {
                if (i.getId().equals(item)) {
                    i.setAddress(i.getCommunityName() + "-" + i.getBuildName() + "-" + i.getUnitName() + "-" + i.getRoomNumber());
                    i.setRegistrationTime(new SimpleDateFormat("yyyy年MM月dd日 hh时mm分ss秒").format(i.getTime1()));
                    data.add(i);
                }
            });
        });*/

        pageData.forEach(i -> {
            i.setAddress(i.getCommunityName() + "-" + i.getBuildName() + "-" + i.getUnitName() + "-" + i.getRoomNumber());
            data.add(i);
        });

        // 单位名称、单位承租人姓名/个人承租人姓名、手机号码、房屋基本信息（小区-楼栋-单元-房号）
        map.put("单位名称", "ownerName");
        map.put("单位承租人姓名/个人承租人姓名", "name");
        map.put("手机号码", "mobile");
        map.put("房屋基本信息", "address");
        map.put("成员登记时间", "operatorTime");

        fileName = "成员信息导出_" + System.currentTimeMillis();
        Workbook workbook = new Export2Util().getExcelByTemplate(data, map, "importAndExport", "成员信息导出.xlsx", 2);
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        // response.setContentType("application/octet-stream;charset=utf-8");
        // ServletOutputStream outputstream = response.getOutputStream();// 取得输出流
        // File file = file(workbook, fileName);
        // File[] srcFiles = {file};
        // File zipFile = new File(contractTmpDir + "ZipFile.zip");
        // zipFiles(srcFiles, zipFile);
        // byte[] zip = File2byte(zipFile);
        // outputstream.write(zip);
        // outputstream.flush();// 刷数据
        // // 关闭
        // workbook.close();
        DownloadUtil downloadUtil = new DownloadUtil();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        workbook.write(bos);
        downloadUtil.download(bos, response, URLEncoder.encode(fileName + ".xlsx", "utf-8"));
        workbook.close();
    }

    /**
     * 将文件转换成byte数组
     */
    public static byte[] File2byte(File tradeFile) {
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(tradeFile);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

    public File file(Workbook workbook, String fileName) throws IOException {

        // 生成文件
        File file = new File(contractTmpDir + fileName + ".xlsx");
        OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            workbook.write(out);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return file;

    }

    public static void zipFiles(File[] srcFiles, File zipFile) {
        // 判断压缩后的文件存在不，不存在则创建
        if (!zipFile.exists()) {
            try {
                zipFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 创建 FileOutputStream 对象
        FileOutputStream fileOutputStream = null;
        // 创建 ZipOutputStream
        ZipOutputStream zipOutputStream = null;
        // 创建 FileInputStream 对象
        FileInputStream fileInputStream = null;

        try {
            // 实例化 FileOutputStream 对象
            fileOutputStream = new FileOutputStream(zipFile);
            // 实例化 ZipOutputStream 对象
            zipOutputStream = new ZipOutputStream(fileOutputStream);
            // 创建 ZipEntry 对象
            ZipEntry zipEntry = null;
            // 遍历源文件数组
            for (int i = 0; i < srcFiles.length; i++) {
                // 将源文件数组中的当前文件读入 FileInputStream 流中
                fileInputStream = new FileInputStream(srcFiles[i]);
                // 实例化 ZipEntry 对象，源文件数组中的当前文件
                zipEntry = new ZipEntry(srcFiles[i].getName());
                zipOutputStream.putNextEntry(zipEntry);
                // 该变量记录每次真正读的字节个数
                int len;
                // 定义每次读取的字节数组
                byte[] buffer = new byte[1024];
                while ((len = fileInputStream.read(buffer)) > 0) {
                    zipOutputStream.write(buffer, 0, len);
                }
            }
            zipOutputStream.closeEntry();
            zipOutputStream.close();
            fileInputStream.close();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    /**
     * 调用待办事项
     *
     * @param communityHouseId 房产id
     * @param userOrgId        个人组织id
     * @param name             人员名称
     * @param operatorId       操作人id
     * @param id               房产成员信息登记表明细表id   saas_community_house_user
     * @param type             1新增同住人  2 新增承租人 3 删除同住人  4 删除承租人
     */
    @Transactional
    public void backlogItem(String communityHouseId, Long userOrgId, String name, String operatorId, Long id, Integer type) {
        log.info("待办事项, communityHouseId={}, userOrgId={}, operatorId={} type={} id={}", communityHouseId, userOrgId, operatorId, type, id);
        Optional<House> optional = houseRepository.findById(communityHouseId);
        // 当前小区、楼宇、单元、房号
        String result = " SELECT sc.name AS residenceCommunityName,scb.name AS buildingNumName,scbu.name AS unitName,sh.room_number AS roomnumber";
        String SQL = " FROM saas_house sh\n" +
                "        LEFT JOIN saas_community sc\n" +
                "        ON sh.residence_community_id = sc.id\n" +
                "        LEFT JOIN saas_community_build scb\n" +
                "        ON sh.building_num = scb.id\n" +
                "        LEFT JOIN saas_community_build_unit scbu\n" +
                "        ON sh.unit = scbu.id\n" +
                "        WHERE sh.id = ? ";
        HouseVO houseVO = jdbcTemplate.queryForObject(result + SQL, new BeanPropertyRowMapper<>(HouseVO.class), communityHouseId);
        String title = "";
        Integer types = null;

        String titleType = "";
        if (type == 1) {
            title = "新增同住人";
            types = BacklogItemTypeEnum.SAVE_NUMBER.getValue();
            titleType = "新增";
        } else if (type == 2) {
            title = "新增承租人";
            types = BacklogItemTypeEnum.SAVE_NUMBER.getValue();
            titleType = "新增";
        } else if (type == 3) {
            title = "删除同住人";
            types = BacklogItemTypeEnum.DELETE_NUMBER.getValue();
            titleType = "删除";
        } else if (type == 4) {
            title = "删除承租人";
            types = BacklogItemTypeEnum.DELETE_NUMBER.getValue();
            titleType = "删除";
        }
        House house = optional.get();
        // 查询当前房产是否有承租人
        List<CommunityHouseUser> communityHouseUser = communityHouseUserRepository.findByCommunityHouseIdAndStatusAndType(communityHouseId, 1, 1);
        if (communityHouseUser != null && communityHouseUser.size() > 0) {
            if (type != 2 && type != 4) {
                // 创建同住人待办事项
                BacklogItem backlogItem = new BacklogItem();
                // 房屋id
                backlogItem.setHouseId(communityHouseId);
                // 如果是公租房取产权单位id，如果是非公租房取物业公司id
                // backlogItem.setOrgId(house.getHouseNature() != null && house.getHouseNature() == 1?house.getOrgId():house.getHousePropertyId());
                // 个人组织id
                backlogItem.setUserOrgId(userOrgId);
                // 待办事项类型
                backlogItem.setType(types);
                // 标题
                backlogItem.setTitle(title + name);
                // 内容
                backlogItem.setContent(houseVO.getResidenceCommunityName() + houseVO.getBuildingNumName() + "栋" + houseVO.getUnitName() + "单元" + houseVO.getRoomNumber() + "号");
                backlogItem.setBusinessStatus("待查看");
                backlogItem.setHandleStatus(0);// 0未读/未处理
                backlogItem.setMatchUserId(communityHouseUser.get(0).getUserId());// 承租人
                backlogItem.setPhone(communityHouseUser.get(0).getMobile());// 手机号
                // 操作人id
                backlogItem.setOperatorId(operatorId);
                // 操作时间
                backlogItem.setCreateTime(new Date());

                // 新增待办事项
                BacklogItem save = backlogItemRepository.save(backlogItem);

                // 房产成员新增/删除 待办事项
                BacklogItemHouseUser houseUser = new BacklogItemHouseUser();
                houseUser.setHouseUserId(id);// 房产成员Id
                houseUser.setBacklogItemId(save.getId());// 待办事项id
                backlogItemHouseUserRepository.save(houseUser);

                // 发送短信
                smsService.sendTemplateSms(communityHouseUser.get(0).getMobile(), smsConfig.getCohabitantTemplateCode());

            }
        }

        /**
         * 1、房屋所属物业，找该物业设置的所有消息接收人
         * 2、房屋设置的省、市、区、街道、社区，找这写区域在层级架构中的所有企业，条件是：企业标签 = 政府机构、主建局、房管局
         *
         * 注：
         * 承租人，新增/删除，只推送消息接收人
         * 同住人，新增/删除，推送承租人 + 消息接收人
         */

        // 所属物业
        Long housePropertyId = house.getHousePropertyId();

        // 所属物业的机构层级关系
        DepartmentHierarchy byOrgId = departmentHierarchyRepository.findByOrgId(housePropertyId);

       /* String sql ="   select b.id , b.mobile as phone  from saas_backlog_item_message_user a \n" +
                "LEFT JOIN saas_user b on b.id=a.user_id \n" +
                "where a.org_id in(select org_id from  saas_department_hierarchy b where b.area_id in (SELECT T2.id FROM ( SELECT @r AS _id,(SELECT @r := parent_id FROM `sys_area` WHERE id = _id) AS parent_id,@l := @l + 1 AS lvl \n" +
                "FROM (SELECT @r := ?, @l := 0) vars,`sys_area` WHERE @r <> 0 AND parent_id >= 0 ) T1 JOIN sys_area T2 ON T1._id = T2.id ORDER BY T1.lvl DESC )) \n ";*/
        // 新增代码事项退送消息类型
        String sql = "SELECT\n" +
                "\tb.id,\n" +
                "\tb.mobile AS phone \n" +
                "FROM\n" +
                "\tsaas_backlog_item_message_user a\n" +
                "\tLEFT JOIN saas_user b ON b.id = a.user_id \n" +
                "\tLEFT JOIN saas_department_hierarchy dh ON dh.org_id = a.org_id\n" +
                "WHERE\n" +
                "\ta.org_id = ? and a.type = 1";

        // 所属区域待办事项消息接收人
        List<AppUser> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(AppUser.class), byOrgId.getOrgId());
        // 推送待办事项
        for (AppUser user : query) {
            BacklogItem backlogItem = new BacklogItem();
            backlogItem.setHouseId(communityHouseId);
            // backlogItem.setOrgId(house.getHouseNature() != null && house.getHouseNature() == 1?house.getOrgId():house.getHousePropertyId());
            backlogItem.setUserOrgId(userOrgId);
            backlogItem.setType(types);
            backlogItem.setTitle(title + name);
            backlogItem.setContent(houseVO.getResidenceCommunityName() + houseVO.getBuildingNumName() + "栋" + houseVO.getUnitName() + "单元" + houseVO.getRoomNumber() + "号");
            backlogItem.setBusinessStatus("待查看");
            backlogItem.setHandleStatus(0);// 0未读/未处理
            backlogItem.setMatchUserId(user.getId());// 承租人
            backlogItem.setPhone(user.getPhone());// 承租人
            backlogItem.setOperatorId(operatorId);
            backlogItem.setCreateTime(new Date());

            BacklogItem save = backlogItemRepository.save(backlogItem);
            BacklogItemHouseUser houseUser = new BacklogItemHouseUser();
            houseUser.setHouseUserId(id);// 房产成员Id
            houseUser.setBacklogItemId(save.getId());// 待办事项id
            backlogItemHouseUserRepository.save(houseUser);


//            if(StringUtils.isNotBlank(user.getPhone())){
//                if (type !=2 || type !=4) {
//                    smsService.sendTemplateSms(user.getPhone(), smsConfig.getCohabitantTemplateCode());
//                }
//            }else{
//            	log.info("待办事项, 短信发送失败, user is null, userId = {}", user.getId());
//            }
        }
    }


    /**
     * 批量调用待办事项
     */
    @Transactional
    public void backlogItemList(List<BacklogItemVo> backlogItemList) {

        log.info("批量调用待办事项, backlogItemList={}", JSONObject.toJSONString(backlogItemList));

        for (BacklogItemVo vo : backlogItemList) {

            Optional<House> optional = houseRepository.findById(vo.getCommunityHouseId());
            String result = " SELECT sc.name AS residenceCommunityName,scb.name AS buildingNumName,scbu.name AS unitName,sh.room_number AS roomnumber";
            String SQL = " FROM saas_house sh\n" +
                    "        LEFT JOIN saas_community sc\n" +
                    "        ON sh.residence_community_id = sc.id\n" +
                    "        LEFT JOIN saas_community_build scb\n" +
                    "        ON sh.building_num = scb.id\n" +
                    "        LEFT JOIN saas_community_build_unit scbu\n" +
                    "        ON sh.unit = scbu.id\n" +
                    "        WHERE sh.id = ? ";
            HouseVO houseVO = jdbcTemplate.queryForObject(result + SQL, new BeanPropertyRowMapper<>(HouseVO.class), vo.getCommunityHouseId());
            String title = "";
            Integer types = null;

            String titleType = "";
            if (vo.getType() == 1) {
                title = "新增同住人";
                types = BacklogItemTypeEnum.SAVE_NUMBER.getValue();
                titleType = "新增";
            } else if (vo.getType() == 2) {
                title = "新增承租人";
                types = BacklogItemTypeEnum.SAVE_NUMBER.getValue();
                titleType = "新增";
            } else if (vo.getType() == 3) {
                title = "删除同住人";
                types = BacklogItemTypeEnum.DELETE_NUMBER.getValue();
                titleType = "删除";
            } else if (vo.getType() == 4) {
                title = "删除承租人";
                types = BacklogItemTypeEnum.DELETE_NUMBER.getValue();
                titleType = "删除";
            }
            House house = optional.get();
            // 判断是否有承租人
            List<CommunityHouseUser> communityHouseUser = communityHouseUserRepository.findByCommunityHouseIdAndStatusAndType(vo.getCommunityHouseId(), 1, 1);
            if (communityHouseUser != null && communityHouseUser.size() > 0) {
                if (vo.getType() != 2 && vo.getType() != 4) {
                    BacklogItem backlogItem = new BacklogItem();
                    backlogItem.setHouseId(vo.getCommunityHouseId());
                    // 如果是公租房取产权单位id，如果是非公租房取物业公司id
                    // backlogItem.setOrgId(house.getHouseNature() != null && house.getHouseNature() == 1?house.getOrgId():house.getHousePropertyId());
                    backlogItem.setUserOrgId(vo.getUserOrgId());
                    backlogItem.setType(types);
                    backlogItem.setTitle(title + vo.getName());
                    backlogItem.setContent(houseVO.getResidenceCommunityName() + houseVO.getBuildingNumName() + "栋" + houseVO.getUnitName() + "单元" + houseVO.getRoomNumber() + "号");
                    backlogItem.setBusinessStatus("待查看");
                    backlogItem.setHandleStatus(0);// 0未读/未处理
                    backlogItem.setMatchUserId(communityHouseUser.get(0).getUserId());// 承租人
                    backlogItem.setPhone(communityHouseUser.get(0).getMobile());// 手机号
                    backlogItem.setOperatorId(vo.getOperatorId());
                    backlogItem.setCreateTime(new Date());

                    BacklogItem save = backlogItemRepository.save(backlogItem);
                    BacklogItemHouseUser houseUser = new BacklogItemHouseUser();
                    houseUser.setHouseUserId(vo.getId());// 房产成员Id
                    houseUser.setBacklogItemId(save.getId());// 待办事项id
                    backlogItemHouseUserRepository.save(houseUser);

                    smsService.sendTemplateSms(communityHouseUser.get(0).getMobile(), smsConfig.getCohabitantTemplateCode());

                }
            } else {
                if (vo.getType() != 2 && vo.getType() != 4) {
                    for (BacklogItemVo backlogItem : backlogItemList) {
                        if (backlogItem.getType() == 2) {

                            BacklogItem item = new BacklogItem();
                            item.setHouseId(vo.getCommunityHouseId());
                            // 如果是公租房取产权单位id，如果是非公租房取物业公司id
                            // backlogItem.setOrgId(house.getHouseNature() != null && house.getHouseNature() == 1?house.getOrgId():house.getHousePropertyId());
                            item.setUserOrgId(vo.getUserOrgId());
                            item.setType(types);
                            item.setTitle(title + vo.getName());
                            item.setContent(houseVO.getResidenceCommunityName() + houseVO.getBuildingNumName() + "栋" + houseVO.getUnitName() + "单元" + houseVO.getRoomNumber() + "号");
                            item.setBusinessStatus("待查看");
                            item.setHandleStatus(0);// 0未读/未处理

                            item.setMatchUserId(backlogItem.getUserId());// 承租人
                            item.setPhone(backlogItem.getPhone());// 手机号

                            item.setOperatorId(vo.getOperatorId());
                            item.setCreateTime(new Date());

                            BacklogItem save = backlogItemRepository.save(item);
                            BacklogItemHouseUser houseUser = new BacklogItemHouseUser();
                            houseUser.setHouseUserId(vo.getId());// 房产成员Id
                            houseUser.setBacklogItemId(save.getId());// 待办事项id
                            backlogItemHouseUserRepository.save(houseUser);

                            smsService.sendTemplateSms(backlogItem.getPhone(), smsConfig.getCohabitantTemplateCode());


                        }


                    }


                }


            }

            /**
             * 1、房屋所属物业，找该物业设置的所有消息接收人
             * 2、房屋设置的省、市、区、街道、社区，找这写区域在层级架构中的所有企业，条件是：企业标签 = 政府机构、主建局、房管局
             *
             * 注：
             * 承租人，新增/删除，只推送消息接收人
             * 同住人，新增/删除，推送承租人 + 消息接收人
             */

            Long housePropertyId = house.getHousePropertyId();

            DepartmentHierarchy byOrgId = departmentHierarchyRepository.findByOrgId(housePropertyId);

            /*String sql ="   select b.id , b.mobile as phone  from saas_backlog_item_message_user a \n" +
                    "LEFT JOIN saas_user b on b.id=a.user_id \n" +
                    "where a.org_id in(select org_id from  saas_department_hierarchy b where b.area_id in (SELECT T2.id FROM ( SELECT @r AS _id,(SELECT @r := parent_id FROM `sys_area` WHERE id = _id) AS parent_id,@l := @l + 1 AS lvl \n" +
                    "FROM (SELECT @r := ?, @l := 0) vars,`sys_area` WHERE @r <> 0 AND parent_id >= 0 ) T1 JOIN sys_area T2 ON T1._id = T2.id ORDER BY T1.lvl DESC )) \n ";*/
            // 所属区域待办事项消息接收人
            String sql = "SELECT\n" +
                    "\tb.id,\n" +
                    "\tb.mobile AS phone \n" +
                    "FROM\n" +
                    "\tsaas_backlog_item_message_user a\n" +
                    "\tLEFT JOIN saas_user b ON b.id = a.user_id \n" +
                    "\tLEFT JOIN saas_department_hierarchy dh ON dh.org_id = a.org_id\n" +
                    "WHERE\n" +
                    "\ta.org_id = ? and a.type = 1";

            List<AppUser> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(AppUser.class), byOrgId.getOrgId());
            log.info(sql + byOrgId.getAreaId());
            for (AppUser user : query) {
                BacklogItem backlogItem = new BacklogItem();
                backlogItem.setHouseId(vo.getCommunityHouseId());
                // backlogItem.setOrgId(house.getHouseNature() != null && house.getHouseNature() == 1?house.getOrgId():house.getHousePropertyId());
                backlogItem.setUserOrgId(vo.getUserOrgId());
                backlogItem.setType(types);
                backlogItem.setTitle(title + vo.getName());
                backlogItem.setContent(houseVO.getResidenceCommunityName() + houseVO.getBuildingNumName() + "栋" + houseVO.getUnitName() + "单元" + houseVO.getRoomNumber() + "号");
                backlogItem.setBusinessStatus("待查看");
                backlogItem.setHandleStatus(0);// 0未读/未处理
                backlogItem.setMatchUserId(user.getId());// 承租人
                backlogItem.setPhone(user.getPhone());// 承租人
                backlogItem.setOperatorId(vo.getOperatorId());
                backlogItem.setCreateTime(new Date());

                BacklogItem save = backlogItemRepository.save(backlogItem);
                BacklogItemHouseUser houseUser = new BacklogItemHouseUser();
                houseUser.setHouseUserId(vo.getId());// 房产成员Id
                houseUser.setBacklogItemId(save.getId());// 待办事项id
                backlogItemHouseUserRepository.save(houseUser);


//            if(StringUtils.isNotBlank(user.getPhone())){
//                if (type !=2 || type !=4) {
//                    smsService.sendTemplateSms(user.getPhone(), smsConfig.getCohabitantTemplateCode());
//                }
//            }else{
//            	log.info("待办事项, 短信发送失败, user is null, userId = {}", user.getId());
//            }
            }

        }

    }

    /**
     * 查询出有承租单位标签的产权机构
     *
     * @param accessToken
     * @return
     */
    public ResultBean<Object> Unitlessee(String accessToken) {
        try {
            TokenRedisVo token = redisService.findTokenVo(accessToken);
            if (token == null) {
                return ResultBean.failedResultOfToken();
            }
            String SQL = " SELECT * FROM `saas_department_hierarchy` dh\n" +
                    "LEFT JOIN saas_department_enterprise_tag_ref detr \n" +
                    "    ON dh.id = detr.dep_ref_id \n" +
                    "WHERE detr.tag_id = 7 AND dh.status = 1 ";
            List<DepartmentHierarchy> query = jdbcTemplate.query(SQL, new BeanPropertyRowMapper<>(DepartmentHierarchy.class));
            return ResultBean.successfulResult(query);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 获取省份3个首字母
     *
     * @param name
     * @return
     */
    public String pinyin(String name) {
        StringBuffer pybf = new StringBuffer();
        char[] arr = name.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < arr.length; i++) {
            if (Character.toString(arr[i]).matches("[\\u4E00-\\u9FA5]+")) {
                try {
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat);
                    if (temp != null) {
                        pybf.append(temp[0].charAt(0));
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pybf.append(arr[i]);
            }
        }
        return pybf.toString().replaceAll("\\W", "").trim().substring(0, 3);
    }

    /**
     * 查询合租房屋下的房屋成员列表
     *
     * @param houseId
     * @return
     */
    public ResultBean<List<CommunityHouseUserVO>> selectList(String accessToken, String houseId, String roomNumber) {
        try {
            TokenRedisVo token = redisService.findTokenVo(accessToken);
            if (token == null) {
                return ResultBean.failedResultOfToken();
            }

            // 查询出合租房产下对应房屋号的房屋信息
            List<House> byHousemateIdAndStatusAndRoomNumber = houseRepository.findByHousemateIdAndStatusAndRoomNumber(houseId, 1, roomNumber);
            String id = null;
            if (byHousemateIdAndStatusAndRoomNumber.size() > 0) {

                id = byHousemateIdAndStatusAndRoomNumber.get(0).getId();
            }
            // 查询未删除的房屋成员列表
            String queryMember = "SELECT schu.*,sau.face_pic AS humanFaceImage, sau.certification_status AS certificationStatus FROM saas_community_house_user schu\n" +
                    "   LEFT JOIN saas_app_user sau\n" +
                    "   ON schu.user_id = sau.id \n" +
                    "   WHERE schu.community_house_id = ? AND schu.status = 1 AND schu.type != 3";
            List<CommunityHouseUserVO> list = jdbcTemplate.query(queryMember, new BeanPropertyRowMapper<>(CommunityHouseUserVO.class), id);
            for (CommunityHouseUserVO communityHouseUserVO : list) {
                // 拼接人脸图片路径 20230411 xiaolong 因为一体机图片路径没有前缀，是自己拼接的
                String humanFaceImage = communityHouseUserVO.getHumanFaceImage();
                if (StringUtils.isNotBlank(humanFaceImage)) {
                    if (StrUtil.startWith(humanFaceImage, "http://") || StrUtil.startWith(humanFaceImage, "https://")) {
                        communityHouseUserVO.setHumanFaceImage(humanFaceImage);
                    } else {
                        humanFaceImage = ossBucketUrl + humanFaceImage;
                        communityHouseUserVO.setHumanFaceImage(humanFaceImage);
                    }
                }

                if (communityHouseUserVO.getRelationTag() != null && communityHouseUserVO.getMobile().contains("_")) {
                    communityHouseUserVO.setMobile(communityHouseUserVO.getMobile().substring(0, communityHouseUserVO.getMobile().indexOf("_")));
                }
            }
            return ResultBean.successfulResult(list);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public List<CommunityHouseUser> findByCommunityHouseIdAndStatusAndType(String houseId, int type, int status) {
        return communityHouseUserRepository.findByCommunityHouseIdAndStatusAndType(houseId, status, type);
    }


    /**
     * 新增同住人信息并进行实名认证并授权智能锁人脸开锁
     *
     * @param accessToken
     * @param accessToken,SaveOrEditVO
     * @return
     * @author shun
     * @date 2023年11月6日
     */
    @Transactional
    public ResultBean<Object> eidAuthentication(String accessToken, CommunityHouseUser communityHouseUser) {
        TokenRedisVo token = redisService.findTokenVo(accessToken);
        if (ObjectUtil.isEmpty(communityHouseUser)) {
            return ResultBean.failedResultOfParamWithMsg("请填写成员信息");
        }
        String name = communityHouseUser.getName();
        String cardNumber = communityHouseUser.getCardNumber();
        if (StrUtil.isEmpty(name) || StrUtil.isEmpty(cardNumber)) {
            return ResultBean.failedResultOfParamWithMsg("请填写姓名/身份证号");
        }
        if (!IdcardUtil.isValidCard(communityHouseUser.getCardNumber())) {
            return ResultBean.failedResultOfParamWithMsg("请输入正确的身份证号");
        }
        if (token == null) {
            return ResultBean.failedResultOfToken();
        }

        CommunityHouseUser byCommunityHouseIdAndStatusAndMobileAndName = communityHouseUserRepository.findByCommunityHouseIdAndStatusAndCardNumberAndName(communityHouseUser.getCommunityHouseId(), 1, communityHouseUser.getCardNumber(), communityHouseUser.getName());
        if (ObjectUtil.isNotEmpty(byCommunityHouseIdAndStatusAndMobileAndName)) {
            return ResultBean.failedResultWithMsg("该同住人已存在");
        }

        if (communityHouseUser.getLabel() == null) {
            communityHouseUser.setLabel(1);
        }
        ResultBean<Object> objectResultBean = new ResultBean<>();
        // 阿里云身份证实名认证接口
        String url = aliEidAuthenticationUrl;
        String appcode = aliEidAuthenticationAppcode;
        Map<String, Object> params = new HashMap<>();
        params.put("idcard", cardNumber);
        params.put("name", name);
        String result = HttpRequest.post(url)
                .header("Authorization", "APPCODE " + appcode)// 头信息，多个头信息多次调用此方法即可
                .form(params)
                .timeout(20000)// 超时，毫秒
                .execute().body();


        try {
            cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(result);
            String resultCode = jsonObject.get("code").toString();
            if (resultCode.equals("0")) {
                String description = jsonObject.getJSONObject("result").getStr("description");


                // 系统判断为同一人
                if (resultCode.equals("0") && description.equals("一致")) {
                    // 新增租户信息
                    CommunityHouseUser communityHouseUser1 = new CommunityHouseUser();
                    // 新增
                    // 新增同住人是否给与查看账单标识
                    Integer accountStatus = communityHouseUser.getAccountStatus();
                    if (accountStatus != null) {
                        if (accountStatus == 1) {
                            communityHouseUser1.setAccountStatus(1);
                        } else {
                            communityHouseUser1.setAccountStatus(2);
                        }
                    }
                    List<CommunityHouseUser> byCommunityHouseIdAndStatus = communityHouseUserRepository.findByCommunityHouseIdAndStatus(communityHouseUser.getCommunityHouseId(), 1);
                    int size = byCommunityHouseIdAndStatus.size() + 1;
                    if (communityHouseUser.getLabel() == 1) {
                        List<CommunityHouseUser> communityHouseUserList = communityHouseUserRepository.findByCommunityHouseIdAndStatusAndType(communityHouseUser.getCommunityHouseId(), 1, 1);
                        if (CollectionUtil.isNotEmpty(communityHouseUserList)) {
                            communityHouseUser1.setMobile(communityHouseUserList.get(0).getMobile() + "_" + size);
                        }
                    } else {
                        List<MatchUserHouse> matchUserHouseList = matchUserHouseRepository.findByHouseId(communityHouseUser.getCommunityHouseId());
                        if (CollectionUtil.isNotEmpty(matchUserHouseList)) {
                            Optional<MatchUser> matchUser = matchUserRepository.findById(Long.valueOf(matchUserHouseList.get(0).getMatchUserStockId()));
                            communityHouseUser1.setMobile(matchUser.get().getPhone() + "_" + size);
                        }
                    }

                    communityHouseUser1.setName(name);
                    communityHouseUser1.setMobileStatus(CommunityHouseUser.MOBILE_STATUS_NO);
                    communityHouseUser1.setStatus(1);
                    communityHouseUser1.setOperatorId(token.getId());
                    communityHouseUser1.setOperatorTime(new Date());
                    communityHouseUser1.setUserType(1);
                    communityHouseUser1.setChangeLabel(1);
                    communityHouseUser1.setCommunityHouseId(communityHouseUser.getCommunityHouseId());
                    communityHouseUser1.setCommunityId(communityHouseUser.getCommunityId());
                    communityHouseUser1.setType(communityHouseUser.getType());
                    communityHouseUser1.setRelationTag(communityHouseUser.getRelationTag());
                    communityHouseUser1.setCardNumber(communityHouseUser.getCardNumber());
                    communityHouseUser1.setOpenPushMessageType("0");
                    communityHouseUser1.setOrderId(communityHouseUser.getOrderId());
                    CommunityHouseUser save = communityHouseUserRepository.save(communityHouseUser1);
                    List<BacklogItemVo> backlogItemList = new ArrayList<>();

                    String houseId = communityHouseUser.getCommunityHouseId();

                    List<SmartLock> lockList = smartLockRepository.findByHouseIdAndStatus(houseId, 1);
                    // 合租房产添加成员如果有绑定智能锁的情况下添加智能锁信息
                    List<House> byIdAndStatus = houseRepository.findByIdAndStatus(houseId, 1);
                    String housemateId = null;
                    if (byIdAndStatus.size() > 0) {
                        housemateId = byIdAndStatus.get(0).getHousemateId();
                    }
                    // 获取合租房产的智能锁信息
                    List<SmartLock> lockSubHouseList = smartLockRepository.findByHouseIdAndStatus(housemateId, 1);

                    if (!lockList.isEmpty() || !lockSubHouseList.isEmpty()) {// 已安装锁
                        SmartLock smartLock = lockList.size() > 0 ? lockList.get(0) : lockSubHouseList.get(0);
                        Long lockId = lockList.size() > 0 ? lockList.get(0).getId() : lockSubHouseList.get(0).getId();

                        BacklogItemVo backlogItemVo = new BacklogItemVo();
                        backlogItemVo.setCommunityHouseId(houseId);// 房产id
                        backlogItemVo.setUserOrgId(token.getEnterpriseId());// 个人组织id
                        backlogItemVo.setName(communityHouseUser.getName());// 人员名称
                        backlogItemVo.setOperatorId(token.getId());// 操作人id
                        backlogItemVo.setId(save.getId());// 房产成员信息登记表明细表id   saas_community_house_user
                        backlogItemVo.setType(1);// 1新增同住人  2 新增承租人 3 删除同住人  4 删除承租人
                        backlogItemVo.setPhone(save.getMobile());// 手机号
                        backlogItemList.add(backlogItemVo);


                        SmartLockAuth auth = new SmartLockAuth();
                        auth.setLockId(lockId);
                        auth.setHouseId(smartLock.getHouseId());
                        auth.setBindType(0);// 单位
                        auth.setMatchUserId(smartLock.getMatchUserId());
                        if (communityHouseUser.getType() == 1) {
                            auth.setUserType(1);
                        } else if (communityHouseUser.getType() == 2) {
                            auth.setUserType(2);
                        } else if (communityHouseUser.getType() == 3) {
                            auth.setUserType(3);
                        } else {
                            auth.setUserType(4);
                        }
                        auth.setUserName(name);
                        auth.setMobile(save.getMobile());

                        if (smartLock.getStatus() == 2) {
                            auth.setPwdStatus(2);
                            auth.setFingerprintStatus(2);
                            auth.setCardStatus(2);
                            auth.setCpuStatus(2);
                            auth.setBleStatus(2);
                            auth.setFaceStatus(2);
                        } else {
                            auth.setPwdStatus(0);
                            auth.setFingerprintStatus(0);
                            auth.setCardStatus(0);
                            auth.setCpuStatus(0);
                            auth.setBleStatus(0);
                            auth.setFaceStatus(0);
                        }
                        auth.setRelationTag(communityHouseUser.getRelationTag());
                        auth.setCreateTime(new Date());
                        auth.setCommunityUserId(save.getId());
                        // 新增合租房屋子房屋Id
                        auth.setSubHouseId(communityHouseUser.getCommunityHouseId());
                        // 新增房屋号
                        List<House> byIdAndStatus1 = houseRepository.findByIdAndStatus(communityHouseUser.getCommunityHouseId(), 1);
                        String num = null;
                        if (byIdAndStatus1.size() > 0) {
                            num = byIdAndStatus1.get(0).getRoomNumber();
                        }
                        auth.setRoomNumber(num);
                        smartLockAuthRepository.save(auth);


                        //	新增流动人员数据
                        //	类型：1租户 2成员 3房屋管理员 4房管员 (3房屋管理员和4房管员不用记录)
                        if (communityHouseUser.getType() == 1 || communityHouseUser.getType() == 2) {
                            UserFloatingPopulationRecord record = new UserFloatingPopulationRecord();
                            record.setUserId(communityHouseUser.getUserId());
                            record.setUserPhone(save.getMobile());
                            record.setUserName(communityHouseUser.getName());
                            record.setHouseId(communityHouseUser.getCommunityHouseId());
                            Optional<House> house1 = houseRepository.findById(communityHouseUser.getCommunityHouseId());
                            House house = house1.get();
                            record.setOrgId(house.getOrgId());
                            record.setType(UserFloatingPopulationRecord.RECORD_TYPE_CHECK_IN);
                            record.setCreateBy(token.getId());
                            record.setCreateTime(new Date());
                            userFloatingPopulationRecordService.insertUserFloatingPopulationRecord(record);
                        }

                        // if (smartLock.getBrandId() == 5 || smartLock.getBrandId() == 6) {
                        //     SmartLockFace smartLockFace = new SmartLockFace();
                        //     smartLockFace.setSn(smartLock.getSn());
                        //     smartLockFace.setFaceImage(communityHouseUser.getHumanFaceImage());
                        //     smartLockFace.setAuthType(SmartLockFace.PERMANENT_FLAG_YES);
                        //     smartLockFace.setLockId(lockId);
                        //     smartLockFace.setLockAuthId(smartLockAuth.getId());
                        //     ResultBean<String> stringResultBean = smartLockBrandService.operationFace(smartLockFace, smartLock.getBrandId());
                        //     String resultData = stringResultBean.getResultData();
                        //     String msg = stringResultBean.getMsg();
                        //     String code = stringResultBean.getCode();
                        //     if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                        //         log.error("LockAppService authPwd---> " + msg);
                        //         throw new RuntimeException(msg);
                        //     }
                        //     smartLockFace.setReturnFaceId(StrUtil.isEmpty(resultData) ? null : Long.valueOf(resultData));
                        //     smartLockFace.setIdentification(resultData);
                        //     smartLockFace.setStatus(1);
                        //     smartLockFace.setCreateTime(new Date());
                        //     smartLockFaceRepository.save(smartLockFace);
                        //     smartLock.setMechineStatus(1);
                        //     smartLockRepository.save(smartLock);
                        // }

                    } else {// 未安装锁
                        BacklogItemVo backlogItemVo = new BacklogItemVo();
                        backlogItemVo.setCommunityHouseId(houseId);// 房产id
                        backlogItemVo.setUserOrgId(token.getEnterpriseId());// 个人组织id
                        backlogItemVo.setName(communityHouseUser.getName());// 人员名称
                        backlogItemVo.setOperatorId(token.getId());// 操作人id
                        backlogItemVo.setId(save.getId());// 房产成员信息登记表明细表id   saas_community_house_user
                        backlogItemVo.setType(1);// 1新增同住人  2 新增承租人 3 删除同住人  4 删除承租人
                        backlogItemVo.setPhone(save.getMobile());// 手机号
                        backlogItemList.add(backlogItemVo);
                        //	新增流动人员数据
                        //	类型：1租户 2成员 3房屋管理员 4房管员 (3房屋管理员和4房管员不用记录)
                        if (communityHouseUser.getType() == 1 || communityHouseUser.getType() == 2) {
                            UserFloatingPopulationRecord record = new UserFloatingPopulationRecord();
                            record.setUserId(communityHouseUser.getUserId());
                            record.setUserPhone(save.getMobile());
                            record.setUserName(communityHouseUser.getName());
                            record.setHouseId(communityHouseUser.getCommunityHouseId());
                            Optional<House> house1 = houseRepository.findById(communityHouseUser.getCommunityHouseId());
                            House house = house1.get();
                            record.setOrgId(house.getOrgId());
                            record.setType(UserFloatingPopulationRecord.RECORD_TYPE_CHECK_IN);
                            record.setCreateBy(token.getId());
                            record.setCreateTime(new Date());
                            userFloatingPopulationRecordService.insertUserFloatingPopulationRecord(record);
                        }
                    }

                    // 待办事项
                    backlogItemList(backlogItemList);
                    objectResultBean.setCode("10000");
                    objectResultBean.setMsg("成功");
                    return objectResultBean;
                } else {
                    objectResultBean.setCode("10001");
                    objectResultBean.setMsg("姓名和身份证号不匹配");
                    return objectResultBean;
                }
            }

            objectResultBean.setCode("10001");
            objectResultBean.setMsg(jsonObject.get("message").toString());
            return objectResultBean;

        } catch (Exception e) {
            log.error(" e={}", e);
            objectResultBean.setCode("10001");
            objectResultBean.setMsg("系统异常，请稍后再试");
            return objectResultBean;
        }
    }

    /**
     * 新增同住人信息并进行实名认证并授权智能锁人脸开锁
     *
     * @param accessToken
     * @param accessToken,SaveOrEditVO
     * @return
     * @author shun
     * @date 2023年11月6日
     */
    @Transactional
    public ResultBean<Object> addUserByOrder(String accessToken, CommunityHouseUser communityHouseUser) {
        TokenRedisVo token = redisService.findTokenVo(accessToken);
        String name = communityHouseUser.getName();
        String cardNumber = communityHouseUser.getCardNumber();
        if (StrUtil.isEmpty(name) || StrUtil.isEmpty(cardNumber)) {
            return ResultBean.failedResultOfParamWithMsg("请填写姓名/身份证号");
        }
        if (!IdcardUtil.isValidCard(communityHouseUser.getCardNumber())) {
            return ResultBean.failedResultOfParamWithMsg("请输入正确的身份证号");
        }
        if (token == null) {
            return ResultBean.failedResultOfToken();
        }
        if (communityHouseUser.getType() == 1) {
            return ResultBean.failedResultWithMsg("不允许添加承租人");
        }

        CommunityHouseUser byCommunityHouseIdAndStatusAndMobileAndName = communityHouseUserRepository.findByCommunityHouseIdAndStatusAndCardNumberAndName(communityHouseUser.getCommunityHouseId(), 1, communityHouseUser.getCardNumber(), communityHouseUser.getName());
        if (ObjectUtil.isNotEmpty(byCommunityHouseIdAndStatusAndMobileAndName)) {
            return ResultBean.failedResultWithMsg("该同住人已存在");
        }

        List<CommunityHouseUser> byCommunityHouseIdAndStatusAndMobile = communityHouseUserRepository.findByCommunityHouseIdAndStatusAndMobile(communityHouseUser.getCommunityHouseId(), 1, communityHouseUser.getMobile());
        if (!byCommunityHouseIdAndStatusAndMobile.isEmpty()) {
            return ResultBean.failedResultWithMsg("成员手机号码不能重复");
        }

        if (communityHouseUser.getLabel() == null) {
            communityHouseUser.setLabel(1);
        }
        ResultBean<Object> objectResultBean = new ResultBean<>();
        String humanFaceImage = communityHouseUser.getHumanFaceImage();
        Boolean result = false;
        if (StrUtil.isNotBlank(humanFaceImage)) {
            // 身份三要素认证
            AuthenticationVo authenticationVo = new AuthenticationVo();
            authenticationVo.setCertName(name);
            authenticationVo.setCertNumber(cardNumber);
            authenticationVo.setOssIdFaceUrl(communityHouseUser.getHumanFaceImage());
            result = initFaceVerifyService.faceAuth(authenticationVo);
        } else {
            // 阿里云身份证实名认证接口,身份二要素认证
            String url = aliEidAuthenticationUrl;
            String appcode = aliEidAuthenticationAppcode;
            Map<String, Object> params = new HashMap<>();
            params.put("idcard", cardNumber);
            params.put("name", name);
            String resultStr = HttpRequest.post(url)
                    .header("Authorization", "APPCODE " + appcode)// 头信息，多个头信息多次调用此方法即可
                    .form(params)
                    .timeout(20000)// 超时，毫秒
                    .execute().body();
            cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(resultStr);
            String resultCode = jsonObject.get("code").toString();
            if (resultCode.equals("0")) {
                String description = jsonObject.getJSONObject("result").getStr("description");
                // 系统判断为同一人
                if (resultCode.equals("0") && description.equals("一致")) {
                    result = true;
                } else {
                    log.error("二要素校验：{}", jsonObject);
                }
            }
        }

        try {
            // 系统判断为同一人
            if (result) {
                // 新增租户信息
                CommunityHouseUser communityHouseUser1 = new CommunityHouseUser();
                // 新增
                // 新增同住人是否给与查看账单标识
                Integer accountStatus = communityHouseUser.getAccountStatus();
                if (accountStatus != null) {
                    if (accountStatus == 1) {
                        communityHouseUser1.setAccountStatus(1);
                    } else {
                        communityHouseUser1.setAccountStatus(2);
                    }
                }
                communityHouseUser1.setName(name);
                communityHouseUser1.setMobileStatus(CommunityHouseUser.MOBILE_STATUS_YES);
                communityHouseUser1.setMobile(communityHouseUser.getMobile());
                communityHouseUser1.setStatus(1);
                communityHouseUser1.setOperatorId(token.getId());
                communityHouseUser1.setOperatorTime(new Date());
                communityHouseUser1.setUserType(1);
                communityHouseUser1.setChangeLabel(1);
                communityHouseUser1.setCommunityHouseId(communityHouseUser.getCommunityHouseId());
                communityHouseUser1.setCommunityId(communityHouseUser.getCommunityId());
                communityHouseUser1.setType(communityHouseUser.getType());
                communityHouseUser1.setRelationTag(communityHouseUser.getRelationTag());
                communityHouseUser1.setCardNumber(communityHouseUser.getCardNumber());
                communityHouseUser1.setOpenPushMessageType("0");
                if (StrUtil.isNotBlank(humanFaceImage)) {
                    humanFaceImage = humanFaceImage.replace(ossBucketUrl, "");
                    communityHouseUser1.setHumanFaceImage(humanFaceImage);
                }
                CommunityHouseUser save = communityHouseUserRepository.save(communityHouseUser1);
                List<BacklogItemVo> backlogItemList = new ArrayList<>();

                String houseId = communityHouseUser.getCommunityHouseId();

                List<SmartLock> lockList = smartLockRepository.findByHouseIdAndStatus(houseId, 1);
                // 合租房产添加成员如果有绑定智能锁的情况下添加智能锁信息
                List<House> byIdAndStatus = houseRepository.findByIdAndStatus(houseId, 1);
                String housemateId = null;
                if (byIdAndStatus.size() > 0) {
                    housemateId = byIdAndStatus.get(0).getHousemateId();
                }
                // 获取合租房产的智能锁信息
                List<SmartLock> lockSubHouseList = smartLockRepository.findByHouseIdAndStatus(housemateId, 1);

                if (!lockList.isEmpty() || !lockSubHouseList.isEmpty()) {// 已安装锁
                    SmartLock smartLock = lockList.size() > 0 ? lockList.get(0) : lockSubHouseList.get(0);
                    Long lockId = lockList.size() > 0 ? lockList.get(0).getId() : lockSubHouseList.get(0).getId();

                    BacklogItemVo backlogItemVo = new BacklogItemVo();
                    backlogItemVo.setCommunityHouseId(houseId);// 房产id
                    backlogItemVo.setUserOrgId(token.getEnterpriseId());// 个人组织id
                    backlogItemVo.setName(communityHouseUser.getName());// 人员名称
                    backlogItemVo.setOperatorId(token.getId());// 操作人id
                    backlogItemVo.setId(save.getId());// 房产成员信息登记表明细表id   saas_community_house_user
                    backlogItemVo.setType(1);// 1新增同住人  2 新增承租人 3 删除同住人  4 删除承租人
                    backlogItemVo.setPhone(save.getMobile());// 手机号
                    backlogItemList.add(backlogItemVo);


                    SmartLockAuth auth = new SmartLockAuth();
                    auth.setLockId(lockId);
                    auth.setHouseId(smartLock.getHouseId());
                    auth.setBindType(0);// 单位
                    auth.setMatchUserId(smartLock.getMatchUserId());
                    if (communityHouseUser.getType() == 1) {
                        auth.setUserType(1);
                    } else if (communityHouseUser.getType() == 2) {
                        auth.setUserType(2);
                    } else if (communityHouseUser.getType() == 3) {
                        auth.setUserType(3);
                    } else {
                        auth.setUserType(4);
                    }
                    auth.setUserName(name);
                    auth.setMobile(save.getMobile());

                    if (smartLock.getStatus() == 2) {
                        auth.setPwdStatus(2);
                        auth.setFingerprintStatus(2);
                        auth.setCardStatus(2);
                        auth.setCpuStatus(2);
                        auth.setBleStatus(2);
                        auth.setFaceStatus(2);
                    } else {
                        auth.setPwdStatus(0);
                        auth.setFingerprintStatus(0);
                        auth.setCardStatus(0);
                        auth.setCpuStatus(0);
                        auth.setBleStatus(0);
                        auth.setFaceStatus(0);
                    }
                    auth.setRelationTag(communityHouseUser.getRelationTag());
                    auth.setCreateTime(new Date());
                    auth.setCommunityUserId(save.getId());
                    // 新增合租房屋子房屋Id
                    auth.setSubHouseId(communityHouseUser.getCommunityHouseId());
                    // 新增房屋号
                    List<House> byIdAndStatus1 = houseRepository.findByIdAndStatus(communityHouseUser.getCommunityHouseId(), 1);
                    String num = null;
                    if (byIdAndStatus1.size() > 0) {
                        num = byIdAndStatus1.get(0).getRoomNumber();
                    }
                    auth.setRoomNumber(num);
                    smartLockAuthRepository.save(auth);


                    //	新增流动人员数据
                    //	类型：1租户 2成员 3房屋管理员 4房管员 (3房屋管理员和4房管员不用记录)
                    if (communityHouseUser.getType() == 1 || communityHouseUser.getType() == 2) {
                        UserFloatingPopulationRecord record = new UserFloatingPopulationRecord();
                        record.setUserId(communityHouseUser.getUserId());
                        record.setUserPhone(save.getMobile());
                        record.setUserName(communityHouseUser.getName());
                        record.setHouseId(communityHouseUser.getCommunityHouseId());
                        Optional<House> house1 = houseRepository.findById(communityHouseUser.getCommunityHouseId());
                        House house = house1.get();
                        record.setOrgId(house.getOrgId());
                        record.setType(UserFloatingPopulationRecord.RECORD_TYPE_CHECK_IN);
                        record.setCreateBy(token.getId());
                        record.setCreateTime(new Date());
                        userFloatingPopulationRecordService.insertUserFloatingPopulationRecord(record);
                    }

                } else {// 未安装锁
                    BacklogItemVo backlogItemVo = new BacklogItemVo();
                    backlogItemVo.setCommunityHouseId(houseId);// 房产id
                    backlogItemVo.setUserOrgId(token.getEnterpriseId());// 个人组织id
                    backlogItemVo.setName(communityHouseUser.getName());// 人员名称
                    backlogItemVo.setOperatorId(token.getId());// 操作人id
                    backlogItemVo.setId(save.getId());// 房产成员信息登记表明细表id   saas_community_house_user
                    backlogItemVo.setType(1);// 1新增同住人  2 新增承租人 3 删除同住人  4 删除承租人
                    backlogItemVo.setPhone(save.getMobile());// 手机号
                    backlogItemList.add(backlogItemVo);
                    //	新增流动人员数据
                    //	类型：1租户 2成员 3房屋管理员 4房管员 (3房屋管理员和4房管员不用记录)
                    if (communityHouseUser.getType() == 1 || communityHouseUser.getType() == 2) {
                        UserFloatingPopulationRecord record = new UserFloatingPopulationRecord();
                        record.setUserId(communityHouseUser.getUserId());
                        record.setUserPhone(save.getMobile());
                        record.setUserName(communityHouseUser.getName());
                        record.setHouseId(communityHouseUser.getCommunityHouseId());
                        Optional<House> house1 = houseRepository.findById(communityHouseUser.getCommunityHouseId());
                        House house = house1.get();
                        record.setOrgId(house.getOrgId());
                        record.setType(UserFloatingPopulationRecord.RECORD_TYPE_CHECK_IN);
                        record.setCreateBy(token.getId());
                        record.setCreateTime(new Date());
                        userFloatingPopulationRecordService.insertUserFloatingPopulationRecord(record);
                    }
                }

                // 待办事项
                backlogItemList(backlogItemList);
                objectResultBean.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
                objectResultBean.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
                return objectResultBean;
            }

            objectResultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            objectResultBean.setMsg("身份信息校验错误！");
            return objectResultBean;

        } catch (Exception e) {
            log.error(" e={}", e.getMessage(), e);
            objectResultBean.setCode(StatusCode.ERROR_CODE_30001.getErrorCode());
            objectResultBean.setMsg(StatusCode.ERROR_CODE_30001.getErrorMsg());
            return objectResultBean;
        }
    }

    /**
     * 新增同住人信息并进行实名认证并授权智能锁人脸开锁
     *
     * @param accessToken
     * @param accessToken,SaveOrEditVO
     * @return
     * @author shun
     * @date 2023年11月6日
     */
    @Transactional
    public ResultBean<Object> editUserByOrder(String accessToken, CommunityHouseUser communityHouseUser) {
        try {
            TokenRedisVo token = redisService.findTokenVo(accessToken);
            if (token == null)
                return ResultBean.failedResultOfToken();


            // bug 2387
            String humanFaceImage = communityHouseUser.getHumanFaceImage();
            Boolean result;
            AuthenticationVo authenticationVo = new AuthenticationVo();
            authenticationVo.setCertName(communityHouseUser.getName());
            authenticationVo.setCertNumber(communityHouseUser.getCardNumber());
            if (StrUtil.isNotBlank(humanFaceImage)) {
                // 身份三要素认证
                authenticationVo.setOssIdFaceUrl(communityHouseUser.getHumanFaceImage());
                result = initFaceVerifyService.faceAuth(authenticationVo);
            } else {
                // 身份二要素认证
                result = initFaceVerifyService.eidAuthentication(authenticationVo);
            }

            if (!result) {
                return ResultBean.failedResultOfParamWithMsg("身份信息校验错误");
            }

            Long id = communityHouseUser.getId();
            String name = communityHouseUser.getName();
            String mobile = communityHouseUser.getMobile();
            Integer type = communityHouseUser.getType();
            String[] split = communityHouseUser.getCommunityHouseId().split(",");
            for (String s : split) {
                if (communityHouseUser.getUserId() != null) {
                    returnMsg(communityHouseUser.getUserId(), s);
                }
            }

            // 编辑时由于特殊关系的手机号码增加了后缀，到时无法编辑保存，优化如下：
            Optional<CommunityHouseUser> userOpt = communityHouseUserRepository.findById(id);
            CommunityHouseUser entity = userOpt.get();
            // 成员类型：1(承租人)租户 2(同住人)成员 3房屋管理员 4房管员
            Integer userType = entity.getType();
            if (userType == 1) {
                return ResultBean.failedResultWithMsg("无法编辑承租人！");
            }
            List<CommunityHouseUser> houseIdAndStatusAndMobile = communityHouseUserRepository.findByCommunityHouseIdAndStatusAndMobile(communityHouseUser.getCommunityHouseId(), 1, communityHouseUser.getMobile());
            if (!houseIdAndStatusAndMobile.isEmpty()) {
                for (CommunityHouseUser houseUser : houseIdAndStatusAndMobile) {
                    if (!id.equals(houseUser.getId())) {
                        return ResultBean.failedResultWithMsg("成员手机号码不能重复");
                    }
                }
            }

            // 编辑时返回的数据，去掉后缀，保存时恢复原数据的后缀，而后继续后续逻辑处理(手机号码是不可编辑的，所以可以这样处理)
            if (entity.getMobile().contains("_")) {
                communityHouseUser.setMobile(entity.getMobile());
            }

            // 特殊关系编辑时不能修改关系类型
            if (communityHouseUser.getRelationTag() != null && entity.getRelationTag() != null && (entity.getRelationTag() == 3 || entity.getRelationTag() == 5) && entity.getRelationTag() != communityHouseUser.getRelationTag()) {
                return ResultBean.failedResultWithMsg("特殊关系(儿子、女儿)同住人，不能修改关系!");
            }

            // 编辑
            Optional<CommunityHouseUser> houseUserOptional = communityHouseUserRepository.findById(id);
            CommunityHouseUser houseUser = houseUserOptional.get();
            String houseId = houseUser.getCommunityHouseId();
            List<CommunityHouseUser> tenantList = communityHouseUserRepository.findByCommunityHouseIdAndStatusAndType(houseId, 1, 1);

            // 查询租户对应的账户信息
            if (token.getLoginType() == 2) {
                // 查询租户对应的账户信息
                AppUser appUser = appUserRepository.findByPhoneAndTypeAndStatus(mobile, UserLoginTypeEnum.CONSUMER.getValue(), 1);
                // 成员也关联，但是不强制验证
                if (appUser != null) {
                    communityHouseUser.setUserId(appUser.getId());
                }
            } else if (token.getLoginType() == 1) {
                // 企业管理员的账户信息
                User user = userRepository.findByMobile(mobile);
                if (user != null) {
                    communityHouseUser.setUserId(user.getId());
                }
            }

            List<SmartLock> lockList = smartLockRepository.findByHouseId(houseId);
            if (!lockList.isEmpty()) {// 已安装锁
                SmartLock smartLock = lockList.get(0);

                // 租户id
                String matchUserId = null;
                String matchUserName = null;
                if (communityHouseUser.getType() == 1) {
                    matchUserId = communityHouseUser.getUserId();
                    matchUserName = communityHouseUser.getName();
                }
                if (communityHouseUser.getType() == 2 && !tenantList.isEmpty()) {
                    matchUserId = tenantList.get(0).getUserId();
                    matchUserName = tenantList.get(0).getName();
                }

                // 更新锁承租人id、姓名
                smartLock.setMatchUserId(matchUserId);
                smartLock.setMatchUserName(matchUserName);
                smartLockRepository.save(smartLock);

                SmartLockAuth auth = smartLockAuthRepository.findByCommunityUserId(id);
                auth.setMatchUserId(matchUserId);
                auth.setAuthorUserId(communityHouseUser.getUserId());
                auth.setUserName(name);
                auth.setMobile(mobile);
                auth.setRelationTag(houseUser.getRelationTag());
                if (communityHouseUser.getType() == 1) {
                    auth.setUserType(1);
                } else if (communityHouseUser.getType() == 2) {
                    auth.setUserType(2);
                } else {
                    auth.setUserType(3);
                }
                smartLockAuthRepository.save(auth);
            }

            communityHouseUser.setStatus(1);
            communityHouseUser.setOperatorId(houseUser.getOperatorId());
            communityHouseUser.setOperatorTime(houseUser.getOperatorTime());
            communityHouseUser.setChangeLabel(1);
            // 新增修复app端上传人脸照后，一体机可以搜到人员信息，人脸无法识别;解决方法修改图片路径
            if (StrUtil.isNotEmpty(humanFaceImage)) {
                humanFaceImage = humanFaceImage.replace(ossBucketUrl, "");
                communityHouseUser.setHumanFaceImage(humanFaceImage);
            }
            communityHouseUserRepository.save(communityHouseUser);

            return ResultBean.successfulResult("success");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<Object> getUserInfo(String accessToken, Long id) {
        TokenRedisVo token = redisService.findTokenVo(accessToken);
        if (token == null) {
            return ResultBean.failedResultOfToken();
        }
        Optional<CommunityHouseUser> houseUser = communityHouseUserRepository.findById(id);

        if (!houseUser.isPresent()) {
            return ResultBean.failedResultWithMsg("查询不到该条数据");
        }
        CommunityHouseUser communityHouseUser = houseUser.get();
        String humanFaceImage = communityHouseUser.getHumanFaceImage();
        if (StrUtil.isNotBlank(humanFaceImage)) {
            communityHouseUser.setHumanFaceImage(ossBucketUrl + humanFaceImage);
        }
        return ResultBean.successfulResult(communityHouseUser);
    }

    public ResultBean<List<House>> selectHouseListByUserId(String accessToken) {
        TokenRedisVo token = redisService.findTokenVo(accessToken);
        if (token == null) {
            return ResultBean.failedResultOfToken();
        }

        Integer flag = token.getFlag();
        String userId = token.getId();
        List<House> houseList = new ArrayList<>();

        List<CommunityHouseUser> houseUsers = communityHouseUserRepository.findCommunityHouseUserByUserIdAndStatus(userId, 1);
        if (CollectionUtil.isEmpty(houseUsers)) {
            return ResultBean.successfulResult(houseList);
        }
        List<String> houseIds = houseUsers.stream().map(CommunityHouseUser::getCommunityHouseId).collect(Collectors.toList());

        for (String houseId : houseIds) {
            Optional<House> byId = houseRepository.findById(houseId);
            if (!byId.isPresent()) {
                continue;
            }
            House house = byId.get();
            Integer houseNature = house.getHouseNature();
            if ((flag == 3 && houseNature != 7) || (flag == 2 && houseNature == 7)) {
                continue;
            }

            SmartLock smartLock = smartLockRepository.findByHouseIdAnAndBrandIdIsFaceLock(houseId);
            if (ObjectUtil.isNull(smartLock)) {
                continue;
            }

            // 构建房屋全路径参数
            String housePath = buildHousePath(house);
            house.setHousePath(housePath);

            List<CommunityHouseUser> communityHouseUsers = communityHouseUserRepository.findByCommunityHouseIdAndStatus(houseId, 1);
            // 过滤承租人和非无手机号用户
            List<CommunityHouseUser> users = communityHouseUsers.stream().filter(m -> m.getType() != 1 && StrUtil.length(m.getMobile()) > 11 && !Objects.equals(m.getUserId(), userId)).collect(Collectors.toList());

            // 校验用户是否已授权
            List<CommunityHouseUser> communityUserList = new ArrayList<>();
            users.forEach(m -> {
                Long communityUserId = m.getId();
                SmartLockAuth smartLockAuth = smartLockAuthRepository.findByHouseIdAndCommunityUserId(houseId, communityUserId);
                if (ObjectUtil.isNotNull(smartLockAuth)) {
                    SmartLockFace smartLockFace = smartLockFaceRepository.findByLockAuthId(smartLockAuth.getId());
                    if (ObjectUtil.isNull(smartLockFace)) {
                        communityUserList.add(m);
                    }
                }
            });

            if (CollectionUtil.isEmpty(communityUserList)) {
                continue;
            }
            house.setCommunityHouseUsers(communityUserList);
            houseList.add(house);
        }

        return ResultBean.successfulResult(houseList);
    }

    public String buildHousePath(House house) {
        StringBuilder housePath = new StringBuilder();
        Community community = communityRepository.findById(house.getResidenceCommunityId()).get();
        String communityName = community.getName();
        housePath.append(communityName).append("小区");
        CommunityBuild communityBuild = communityBuildRepository.findById(house.getBuildingNum()).get();
        String communityBuildName = communityBuild.getName();
        housePath.append(communityBuildName).append("栋");
        CommunityBuildUnit communityBuildUnit = communityBuildUnitRepository.findById(house.getUnit()).get();
        String unitName = communityBuildUnit.getName();
        housePath.append(unitName).append("单元");
        return housePath.toString();

    }

    /**
     * 长时间未开门人员进行信息提醒定时任务
     */
    public void openPushMessageTask() {
        DateTime nowTime = DateUtil.date();
        List<Department> departmentList = departmentRepository.findAll();
        // 查询
        for (Department department : departmentList) {
            if (department.getOpenPushMessageDay() == null || department.getOpenPushMessageDay() <= 0) {
                continue;
            }
            List<BacklogItem> backlogItemList = new ArrayList<>();
            // saas_community_house_user 的id为smart_lock_auth的community_user_id
            List<com.haixiaoke.saas.repository.pojo.User> userList = iUserService.selectUserByTypeAndOrgId(7, department.getId());
            if (CollectionUtil.isEmpty(userList)) {
                log.error("查询不到接收代办事项管理人员的数据，userList:{}", userList);
                continue;
            }
            if ("0".equals(department.getOpenPushMessageType())) {
                List<SmartLock> smartLocks = smartLockRepository.findByOrgId(department.getId());
                if (CollectionUtil.isEmpty(smartLocks)) {
                    log.error("查询不到智能锁数据，smartLocks:{}", smartLocks);
                    continue;
                }
                List<String> houseIds = smartLocks.stream().map(SmartLock::getHouseId).collect(Collectors.toList());
                List<House> houseList = houseRepository.findByIdIn(houseIds);
                if (CollectionUtil.isEmpty(houseList)) {
                    log.error("所有用户信息推送--查询不到房屋数据，houseList:{}", houseList);
                    continue;
                }
                Map<String, House> houseMap = houseList.stream().collect(Collectors.toMap(House::getId, House -> House));
                // 小区id集合
                List<String> communityIds = houseList.stream().map(House::getResidenceCommunityId).collect(Collectors.toList());
                Map<String, Community> communityMap = communityRepository.findByIdIn(communityIds).stream().collect(Collectors.toMap(Community::getId, Community -> Community));
                // 楼栋id集合
                List<Long> communityBuildIds = houseList.stream().map(House::getBuildingNum).collect(Collectors.toList());
                Map<Long, CommunityBuild> buildMap = communityBuildRepository.findByIdIn(communityBuildIds).stream().collect(Collectors.toMap(CommunityBuild::getId, CommunityBuild -> CommunityBuild));
                // 单元id集合
                List<Long> unitIds = houseList.stream().map(House::getUnit).collect(Collectors.toList());
                Map<Long, CommunityBuildUnit> unitMap = communityBuildUnitRepository.findByIdIn(unitIds).stream().collect(Collectors.toMap(CommunityBuildUnit::getId, CommunityBuildUnit -> CommunityBuildUnit));
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日");
                if (CollectionUtil.isNotEmpty(smartLocks)) {
                    List<Long> lockIds = smartLocks.stream().map(SmartLock::getId).collect(Collectors.toList());
                    List<SmartLockAuth> smartLockAuthList = smartLockAuthRepository.findByLockIdIn(lockIds);
                    for (SmartLockAuth smartLockAuth : smartLockAuthList) {
                        LockOpenLog lockOpenLog = lockOpenLogRepository.findByUserId(smartLockAuth.getId());
                        if (ObjectUtil.isEmpty(lockOpenLog)) {
                            continue;
                        }
                        long betweenDay = DateUtil.between(lockOpenLog.getOpenTime(), nowTime, DateUnit.DAY);
                        if (department.getOpenPushMessageDay() == betweenDay) {
                            for (com.haixiaoke.saas.repository.pojo.User user : userList) {
                                // 房屋
                                House house = houseMap.get(smartLockAuth.getHouseId());
                                // 小区
                                Community community = communityMap.get(house.getResidenceCommunityId());
                                // 楼栋
                                CommunityBuild build = buildMap.get(house.getBuildingNum());
                                // 单元
                                CommunityBuildUnit unit = unitMap.get(house.getUnit());

                                BacklogItem backlogItem = new BacklogItem();
                                backlogItem.setHouseId(smartLockAuth.getHouseId());
                                backlogItem.setOrgId(department.getId());
                                backlogItem.setType(BacklogItemTypeEnum.UN_OPEN_PUSH_MESSAGE.getValue());
                                backlogItem.setTitle(smartLockAuth.getUserName() + "长时间未开门提醒");
                                backlogItem.setContent("房屋信息：" + community.getName() + build.getName() + "栋" + unit.getName() + "单元" + house.getRoomNumber() + "号" + "\n" +
                                        "人员信息：" + smartLockAuth.getUserName() + "   " + smartLockAuth.getMobile() + "\n" +
                                        "该住户" + dateFormat.format(lockOpenLog.getOpenTime()) + "-" + dateFormat.format(nowTime) + "长时间未开门，请核实情况。");
                                backlogItem.setBusinessStatus("待查看");
                                backlogItem.setHandleStatus(0);// 0未读/未处理
                                backlogItem.setCreateTime(nowTime);
                                backlogItem.setMatchUserId(user.getId());
                                backlogItem.setPhone(user.getMobile());
                                backlogItemList.add(backlogItem);
                            }
                        }
                    }
                }
            } else if ("1".equals(department.getOpenPushMessageType())) {
                List<House> houseList = houseRepository.findByOrgId(department.getId());
                if (CollectionUtil.isEmpty(houseList)) {
                    log.error("重点关注人群信息推送--查询不到房屋数据，houseList:{}", houseList);
                    continue;
                }
                List<String> houseIds = houseList.stream().map(House::getId).collect(Collectors.toList());
                String sql = "SELECT * FROM saas_community_house_user WHERE community_house_id IN " + SqlUtils.foreachIn(houseIds.size()) + " AND open_push_message_type = 1";
                List<CommunityHouseUser> communityHouseUserList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(CommunityHouseUser.class), houseIds.toArray());
                // 查询重点关注人员数据
                if (CollectionUtil.isEmpty(communityHouseUserList)) {
                    log.error("未查询到未开门重点人员信息推送，communityHouseUserList：{}", communityHouseUserList);
                    continue;
                }
                List<Long> communityHouseUserIds = communityHouseUserList.stream().map(CommunityHouseUser::getId).collect(Collectors.toList());
                List<SmartLockAuth> smartLockAuthList = smartLockAuthRepository.findByCommunityUserIdIn(communityHouseUserIds);

                Map<String, House> houseMap = houseList.stream().collect(Collectors.toMap(House::getId, House -> House));
                // 小区id集合
                List<String> communityIds = houseList.stream().map(House::getResidenceCommunityId).collect(Collectors.toList());
                Map<String, Community> communityMap = communityRepository.findByIdIn(communityIds).stream().collect(Collectors.toMap(Community::getId, Community -> Community));
                // 楼栋id集合
                List<Long> communityBuildIds = houseList.stream().map(House::getBuildingNum).collect(Collectors.toList());
                Map<Long, CommunityBuild> buildMap = communityBuildRepository.findByIdIn(communityBuildIds).stream().collect(Collectors.toMap(CommunityBuild::getId, CommunityBuild -> CommunityBuild));
                // 单元id集合
                List<Long> unitIds = houseList.stream().map(House::getUnit).collect(Collectors.toList());
                Map<Long, CommunityBuildUnit> unitMap = communityBuildUnitRepository.findByIdIn(unitIds).stream().collect(Collectors.toMap(CommunityBuildUnit::getId, CommunityBuildUnit -> CommunityBuildUnit));
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日");

                for (SmartLockAuth smartLockAuth : smartLockAuthList) {
                    LockOpenLog lockOpenLog = lockOpenLogRepository.findByUserId(smartLockAuth.getId());
                    if (ObjectUtil.isEmpty(lockOpenLog)) {
                        continue;
                    }
                    long betweenDay = DateUtil.between(lockOpenLog.getOpenTime(), nowTime, DateUnit.DAY);
                    if (department.getOpenPushMessageDay() == betweenDay) {
                        for (com.haixiaoke.saas.repository.pojo.User user : userList) {
                            // 房屋
                            House house = houseMap.get(smartLockAuth.getHouseId());
                            // 小区
                            Community community = communityMap.get(house.getResidenceCommunityId());
                            // 楼栋
                            CommunityBuild build = buildMap.get(house.getBuildingNum());
                            // 单元
                            CommunityBuildUnit unit = unitMap.get(house.getUnit());

                            BacklogItem backlogItem = new BacklogItem();
                            backlogItem.setHouseId(smartLockAuth.getHouseId());
                            backlogItem.setOrgId(department.getId());
                            backlogItem.setType(BacklogItemTypeEnum.UN_OPEN_PUSH_MESSAGE.getValue());
                            backlogItem.setTitle(smartLockAuth.getUserName() + "长时间未开门提醒");
                            backlogItem.setContent("房屋信息：" + community.getName() + build.getName() + "栋" + unit.getName() + "单元" + house.getRoomNumber() + "号" + "\n" +
                                    "人员信息：" + smartLockAuth.getUserName() + "   " + smartLockAuth.getMobile() + "\n" +
                                    "该住户" + dateFormat.format(lockOpenLog.getOpenTime()) + "-" + dateFormat.format(nowTime) + "长时间未开门，请核实情况。");
                            backlogItem.setBusinessStatus("待查看");
                            backlogItem.setHandleStatus(0);// 0未读/未处理
                            backlogItem.setCreateTime(nowTime);
                            backlogItem.setMatchUserId(user.getId());
                            backlogItem.setPhone(user.getMobile());
                            backlogItemList.add(backlogItem);
                        }
                    }
                }
            }
            backlogItemRepository.saveAll(backlogItemList);
        }
    }

    public ResultBean<String> updateopenPushMessageType(String accessToken, CommunityHouseUser communityHouseUser) {
        TokenRedisVo token = redisService.findTokenVo(accessToken);
        if (token == null) {
            return ResultBean.failedResultOfToken();
        }
        Optional<CommunityHouseUser> houseUser = communityHouseUserRepository.findById(communityHouseUser.getId());
        if (!houseUser.isPresent()) {
            return ResultBean.failedResultWithMsg("查询不到该成员");
        }
        CommunityHouseUser findHouseUser = houseUser.get();
        findHouseUser.setOpenPushMessageType(communityHouseUser.getOpenPushMessageType());
        communityHouseUserRepository.save(findHouseUser);
        return ResultBean.successfulResult("success");
    }
}
